Nginx – Clean URLs and php extension on nginx

nginxPHPrewrite

I've looked at dozens of other questions and references on the web – and by all my calculations, my setup should work, but it doesn't.

I have nginx installation with php-fpm. If I try to access a .php file, it runs correctly and I get the correct results. I got this in my config file:

location ~ \.php$ {
    try_files $uri =404;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;
}

Now, I want to setup my web app so that /somedir/file automatically executes /somdir/file.php while still displaying /somdir/file in the browser's address bar. So I modified my config to contain the following:

location / {
    try_files $uri $uri/ $uri.php?query_string
}

This kind of works, that is, the server does access the .php file. Yet, instead of executing it using the existing location ~ \.php$ block above, it simply spits the php source code as the download into the browser. If I append the .php manually to the requested URL, then the php is executed.

It feels as if once the server matches try_files to $uri.php, it then does not do another pass at locations to see that what it needs to do with the php files. I tried putting the php block above and below the location /, but it makes no difference.

How can I get the php to be executed?

Best Answer

Did you try with the rewrite directive? For example:

location / {
    try_files $uri $uri/ @extensionless-php;
    index index.html index.htm index.php;
} 

location ~ \.php$ {
    try_files $uri =404;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;
}

location @extensionless-php {
    rewrite ^(.*)$ $1.php last;
}

Source: http://www.tweaktalk.net/60/nginx-remove-php-file-extension-from-url