aditseng
aditseng

Reputation: 99

URI rewrite with nginx and php-fpm with parameters

I have a bunch of different rules on my nginx server with php-fpm.

The simple one is a rewrite that changes http://server/$1?param=1 to http://server/$1.php?param=1 using

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

I also need to rewrite http://server/abc/123 to http://server/abc.php/123 and also have this processed by the php-fpm

This is the fast-cgi code:

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;

}

and this is the location rewrite

location @abc-php {
    rewrite ^(.*)/abc/(.*)$ $1/photo.php/$2 last;
}

But I keep getting a 404. I'm not sure where I'm going wrong and any help would be appreciated.

Upvotes: 1

Views: 887

Answers (1)

Richard Smith
Richard Smith

Reputation: 49702

You don't show how the named location @abc-php is invoked. I suspect that you have something like this to managed the extensionless PHP:

location / {
    try_files $uri $uri/ @extensionless-php;
}

Your new rewrite rule can be added to the existing named location, like this:

location @extensionless-php {
    rewrite ^(.*)/abc/(.*)$ $1/photo.php/$2 last;
    rewrite ^(.*)$ $1.php last;
}

However, your fast-cgi block is incapable of handing the path_info, so you will need to look here for conventional wisdom, or use something like this:

location ~ ^(?<script>.*\.php)(?<pathinfo>.*)$ {
    try_files $script =404;
    include fastcgi_params; 
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $pathinfo;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
}

Upvotes: 2

Related Questions