nginx strip URI parameter

Viewed 105
  1. there is a nginx with php-fpm installed. there is a subdirectory /shop with main.php inside.
  2. main.php works in a following way: if request is example.com/shop/product/123 - it's requesting example.com/shop/main.php?route=/product/123/ (this works with nginx+apache)

here is the .htaccess content

RewriteCond %{REQUEST_URI} !\.(ico|jpg|png|img)$ 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) main.php?route=$1

What I've tried to do:

location ^~ /shop/product {
    try_files $uri $uri/ @rewrite;
}
location @rewrite {
try_files $uri $uri/ /shop/main.php?route=$1 ;
}

-- this is not working, it is returning a 404

location /shop {
try_files $uri $uri/ /shop/main.php?route=$uri;
}

this returns incorrect page because $uri is /shop/product/123

What I'm trying to achieve is to strip 'shop' word from $uri.

1 Answers

Using second try_files doesn't make sense at all, it is just an extra overhead (two kernel stat calls). Moreover, the $1 variable takes some value after doing some matching against a regex pattern containing a numbered capture group, which isn't a job for the try_files directive. Use rewrite directive instead:

location /shop/ {
    try_files $uri $uri/ @rewrite;
}
location @rewrite {
    rewrite ^/shop(/.*) /shop/main.php?route=$1 last;
}
Related