nginx case insensitive rewrite

Solution 1:

I just had (and fixed) this same problem and ended up here trying to find the answer. The nginx documentation (http://nginx.org/en/docs/http/ngx_http_rewrite_module.html), does not clearly state that the ~* only works inside an if statement, but apparently, that is the case.

To get case-insensitive regular expression matching for an ngnix URL rewrite outside of an if statement, I had to use the Apache/Perl style:

rewrite "(?i)foobar" http://www.youtube.com/watch?v=oHg5SJYRHA0 redirect;

See http://perldoc.perl.org/perlretut.html (search for insensitive). It also seems that prefixing (?i) outside of a specific capture group makes it apply to the whole search string. Note: This does NOT seem to work with "^(?i)foobar" because it seems that the "^" is implied.

Just to be sure, though, and to make any future rewrites easier to maintain and less ambiguous if you end up doing a bunch of them, you may want to do something like this:

location /foobar {
     rewrite "(?i)" http://www.youtube.com/watch?v=oHg5SJYRHA0 redirect;
}

Hope this helps...

Solution 2:

What I've found to make this work:

rewrite ^/foobar http://www.youtube.com/watch?v=oHg5SJYRHA0 redirect;

You only need to do this:

rewrite (?i)^/foobar http://www.youtube.com/watch?v=oHg5SJYRHA0 redirect;

This just means prepend (?i) and otherwise everything is the same for matching.

Solution 3:

Working on a website right now I found this seems to work in a simple way. In the server block, you just need to add the location entries in order like this:

#This rule processes the lowercase page request.
#The (~) after the location tag specifies it is case sensitive
# so it overrides the next rule, which would continuously redirect
location ~ /index[.]html {
#process the index.html page       
}

#This rules rewrites the index request which may be non-case-sensitive
# to all lowercase so the previous rule can process it.
location ~* /index[.]html {
   rewrite ^(.*)$ $scheme://$http_host/index.html redirect;
}