Search code examples
phpnginxfastcgi

How to send all requests through FastCGI with Nginx


Currently, my Nginx server is set up to accept both www.example.com/file and www.example.com/file.php to load file.php. However, because the Nginx setup looks like this:

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;

    // More setup stuff
}

The only way it processes the file as PHP through FastCGI is if the URI ends with .php, otherwise, it will just download the file. How can I set it up so all PHP files get processed through FastCGI, regardless of the URI? (I'm sure this is more secure anyway, so people can't look at my PHP code.)


Solution

  • Although I think it would be better to handle routes of requests not ending in .php through a single php file (ie. index.php), you could try something like this:

    location / {
        root            /path/to/htdocs;
        index           index.php;
        if (-e $request_filename.php) {
              rewrite   ^(.*)?$ /$1.php last;
              break;
        }
        # rewrite requests without matching file index.php (request in: $_GET['req'])
        if (!-e $request_filename) {
              rewrite   ^(.*)?$ /index.php?req=$1 last;
              break;
        }
    }
    
    location ~ \.php$ {
       root             /path/to/htdocs;
       fastcgi_pass     unix:/var/www/php-fpm/nginx.sock;
       fastcgi_index    index.php;
       include          fastcgi_params;
       fastcgi_param    SCRIPT_FILENAME $document_root$fastcgi_script_name;
       ..
    }