Nginx Regex – How to Rewrite URL with Special Characters in Nginx

nginxregexrewrite

How to write a regex that matches a path node with reserved characters like '+','-' ? for example:

https://e.example.com/foo+/bar/file/test.txt need to be re-written as https://e.example.com/bar/file/test.txt

I tried rewrite ^/foo+(/.*)$ break; but it couldn't match the string.

Any suggestions?

Best Answer

In nginx rewrite directive uses the normalized URI for matching. Normalized URI does not include query arguments or indexed search arguments.

You might be able to use a map here:

map $request_uri $filefromarg {
    ^[^+]*\+(.*)$ $1;
    default $request_uri;
}

And in the server block you would have:

try_files $filefromarg $uri =404;

The map takes $request_uri, which contains the full path to resource and query arguments. The first line regular expression captures everything after + sign and sets it to $filefromarg variable.

Then, in the try_files section that is used as the path to check for resource to serve.

Related Topic