Nginx: Remove .php file extension from URL

I spent some time searching the Internet for how to get Nginx to run PHP scripts while omitting the .php file extension in the web address. For example, I wanted www.domain.tld/products to execute products.php. I did not find what I was looking for, so I came up with a solution on my own, which is published below. I was using Nginx version 1.2.1.

I left out some location blocks that are not relevant. Please note that this configuration is intended for when Nginx and PHP fastcgi are running on the same server.


server {
    listen       80;
    server_name  www.domain.tld;
    root         /srv/www/domain.tld/html;
    access_log   /srv/www/domain.tld/log/access.log;
    error_log    /srv/www/domain.tld/log/error.log;

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

    location ~ \.php$ {
        try_files $uri =404;
        include       /etc/nginx/fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

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

Remember to restart the Nginx web server after changing the configuration:
/etc/init.d/nginx restart

This is how it works:
If the requested address is not an existing file or directory (evaluated by try_files in the location / block), and does not already end with .php (handled by the PHP location block), then try to add .php to the address (by using rewrite). This will then be handled by the PHP location block. If this is not an existing file, try_files in the PHP location block will return error 404 to the client. If the .php-file exists, the file name will be passed to PHP fastcgi for execution.

If you have a better solution or if you find any vulnerability in this solution, please let me know.