Home > Net >  nginx rewrite url missing something
nginx rewrite url missing something

Time:12-29

I have multiple dynamic urls at the root directory which needs to be written as following. e.g.

https://mv.test/review/4
https://mv.test/investment-banker/banking-products--004

1st url /Reviews/ is working perfectly fine but 2nd url is going to 404 page. I am not able to understand why it's not working.

Location blocks

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

location /review/ {
    rewrite "^/review/([0-9] )$" /review.php?id=$1 last;
}
location /store/ {
    rewrite "^/(.*)/(.*)$" /store.php?store_type=$1&store_owner=$2 last;
}

CodePudding user response:

Clearly https://example.com/investment-banker/banking-products--004 does not match location /store/, so it will be processed by the default location which is location /.

You want to rewrite https://foo/bar to /store.php?store_type=foo&store_owner=bar for any foo/bar that does not match another legitimate URI already handled by the server.

At the moment the location @extensionless-php block will blindly rewrite the URL to /foo/bar.php whether the PHP file exists or not.

This can be improved with an if block.

For example:

location / {
    try_files $uri $uri.html $uri/ @extensionless-php;
}
location @extensionless-php {
    if (-f $document_root$uri.php) {
        rewrite ^(.*)$ $1.php last;
    }
    rewrite ^/([^/] )/([^/] )$ /store.php?store_type=$1&store_owner=$2 last;
}    
location /review/ {
    rewrite ^/review/([0-9] )$ /review.php?id=$1 last;
}
  • Related