1
votes

When using a map file to rewrite a large number of locations to their destinations:

rewrite ^ $my_redirect_map permanent;

Inside the map file, some redirects look like this (including trailing slash):

/foo/ /bar;

However, if nginx receives a request without a trailing slash, e.g. http://example.com/foo then the redirect doesn't occur.

It can be worked around by including duplicates of every entry in the map file (with and without the trailing slash.)

But is there some way to instruct nginx to ignore the trailing slash when processing the rewrite? It should work the other way too, ie. if the map file says /foo and the request says /foo/ it should match.

1

1 Answers

1
votes

The problem is with the initial match in the map file. You cannot fix this problem at the rewrite statement.

The simplest solution would be to use a regular expression in the map directive's include file:

~^/foo/? /bar;

However, a less elegant solution would be to use two map directives, both including the same file of mappings:

map $uri $without {
    include /path/to/file;
}
map $uri/ $with {
    include /path/to/file;
}

server {
    ...
    if ($with) { return 301 $with; }
    if ($without) { return 301 $without; }
    ...
}

But the include file will need to specify a trailing / in order to match both cases.

See this document for details.