Nginx rewrite issue

Majster asked:

I would like a particular configuration for one of my virtual servers but I have a problem explaining that to Nginx 🙂

Its quite simple. If the URI looks like

example.com/whatever_1/whatever_2/.../whatever_n

I would like to rewrite it as

example.com/index.php?request=whatever_1/whatever_2/.../whatever_n

The second is if the URI begins with /administration/ like

example.com/administration/whatever_1/.../whatever_n

I would like it to be rewritten as

example.com/administration/index.php?request=whatever_1/.../whatever_n

I was tinkering arround and tried:

server
{
#   listen 80;
    server_name example.com;
    index index.html index.php;
    root /srv/example/;

    location ~ /administration/(.*)$
    {
        if (!-e $request_filename)
        {
            rewrite ^/(.*)$ /administration/index.php?request=$1 last;
        }
        break; #tried with and without it
    }

    location / #tried with and without this location block
    {
        if (!-e $request_filename)
        {
            #rewrite ^/(.*)$ /index.php?/$1 last;
            rewrite ^/(.*)$ /index.php?request=$1 last;
        }
    }

    location ~ .php$ #boilerplate
        {
                # Filter out arbitrary code execution
                fastcgi_index index.php;
                include fastcgi_params;
                fastcgi_pass  unix:/var/run/php5-fpm.sock;
        }
}

But this does not work. Im quite new to Nginx so any help would be appreciated.

Thanks, Jan.

My answer:


This is nginx, not apache. You should avoid rewrites when possible (and it often is possible).

Use try_files instead. For example:

location /administration/ {
    try_files $uri $uri/ /administration/index.php?request=$request_uri;
}

location / {
    try_files $uri $uri/ /index.php?request=$request_uri;
}

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.