Nginx & Handling Files Without Extension

Just updating (in case anyone finds this useful) that I got it to work, eventually.

This is the configuration that did the trick:

server {
    listen 80;

    root /var/www;
    index index.html index.htm index.php;

    server_name localhost;

    location / {
        if (!-e $request_filename){
            rewrite ^(.*)$ /$1.php;
        }
        try_files $uri $uri/ =404;
    }

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

    try_files $uri $uri/ $uri.html @extensionless =404;

Yes, @extensionless is treated like a normal file, and that's because you've added an extra =404 after @extensionless within try_files -- the @extensionless part would only work as the last parameter as an internal redirect to another context.

If you want not only to support handing requests without .php, but to also strip .php from any requests, you might want to do the following:

location / {
    if (-e $request_filename.php){
        rewrite ^/(.*)$ /$1.php;
    }
}
location ~ \.php$ {
    if ($request_uri ~ ^/([^?]*)\.php(\?.*)?$) {
        return 302 /$1$2;
    }
    fastcgi_...
}

It is much better to avoid using slow rewrite and evil if by the fastest and simplest way:

location ~ ^(.*)\.php$ # If PHP extension then 301 redirect to semantic URL
{
    return 301  $scheme://$server_name$1$is_args$args;
}
location ~ ^/(.*)
{
    try_files $uri.php @static; # If static, serve it in @static
    include fastcgi_params; # if semantic, serve it here
    fastcgi_param SCRIPT_FILENAME $document_root/$1.php;
}
location @static
{
    try_files $uri =404;
}

Tags:

Nginx