×

Clean URL's in Nginx

soap

Published: November 07, 2010

Quick post to let everyone know of a good trick I just figured out. Most clean URL's are created through a rewrite and query page that does all the work. Sometimes though you just want to have a couple php scripts that you can link to like https://oldstatic.travisberry.com/example

In Apache this is trivial. In Nginx, you can spend a couple days trying to get right.

Turns out the solution is simple. If you use a block of code like this

## Parse all .php file in the /var/www directory
location ~ .php$
       location ~ .php$ {
       fastcgi_split_path_info ^(.+.php)(.*)$;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /var/www$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_param  QUERY_STRING     $query_string;
        fastcgi_param  REQUEST_METHOD   $request_method;
        fastcgi_param  CONTENT_TYPE     $content_type;
        fastcgi_param  CONTENT_LENGTH   $content_length;
        fastcgi_intercept_errors        on;
        fastcgi_ignore_client_abort     off;
        fastcgi_connect_timeout 60;
        fastcgi_send_timeout 180;
        fastcgi_read_timeout 180;
        fastcgi_buffer_size 128k;
        fastcgi_buffers 4 256k;
        fastcgi_busy_buffers_size 256k;
        fastcgi_temp_file_write_size 256k;
    }

to turn on PHP, just replace the location with

location ~ $

and comment out

##fastcgi_split_path_info ^(.+.php)(.*)$;

Your code block should now look like

Now instead of linking to /example.php, you can save the file with no extension, put it on your server, and link to /example

Nginx will now handle files without and extension as PHP files. This is a solution that will only fit a limited number of use cases, but compared to writing a rewrite wrapper, this is quick and easy.