14

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?

Thanks.

8

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

26

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.

  • 4
    This should be the accepted answer. – thekingoftruth Sep 5 '14 at 8:55
  • 2
    Thank you. So simple, and yet so hard to find in Nginx docs. Much appreciate the concise pointer! – PKHunter May 2 '17 at 12:10

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.