I am trying to make my nginx redirects as clean as possible. I understand ~* is for case insensitive but I can only get it to work in example 2.

Example 1

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

Example 2 -This works, but it isn't as efficient as the line above.

if ( $request_filename ~* foobar ) {
         rewrite ^ http://www.youtube.com/watch?v=oHg5SJYRHA0 redirect;

Is there a way to do case insensitive redirects with example 1 without getting it too muddy?


3 Answers 3


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...


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.


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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.