Nginx: Rewriting directory path to file

Doug asked:

I’m a little new to Nginx here so bear with me –

I want to rewrite a url like foo.bar.com/newfoo?limit=30 to foo.bar.com/newfoo.php?limit=30.

Seems pretty simple to do it something like this rewrite ^([a-z]+)(.*)$ $1.php$2 last;

The part that I am confused about is where to put it – I’ve tried my hand at a some location directives but I’m doing it wrong.

Here’s my existing virtual host config, where should I implement my rewrite?

server {
listen   80;
listen   [::]:80;

server_name foo.bar.com;
root /home/foo;

index index.php index.html index.htm;

location / {
    try_files $uri $uri/ /index.html;
}

location /doc/ {
    alias /usr/share/doc/;
    autoindex on;
    allow 127.0.0.1;
    deny all;
}

location ~ .php$ {
    try_files $uri =404;

    fastcgi_split_path_info ^(.+.php)(/.+)$;
    include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass unix:/tmp/php5-fpm.sock;
    fastcgi_index index.php;

}
}

Thanks!

My answer:


try_files $uri $uri/ $uri.php /index.html;

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.