Nginx location “not equal to” regex

2019-01-13 20:04发布

How do I set a location condition in Nginx that responds to anything that isn't equal to the listed locations?

I tried:

location !~/(dir1|file2\.php) {
   rewrite ^/(.*) http://example.com/$1 permanent;
}

But it doesn't trigger the redirect. It simply handles the requested URI using the rules in the rest of the server configuration.

3条回答
叼着烟拽天下
2楼-- · 2019-01-13 20:28

i was looking for the same. and found this solution.

Use negative regex assertion:

location ~ ^/(?!(favicon\.ico|resources|robots\.txt)) { 
.... # your stuff 
} 

Source Negated Regular Expressions in location

查看更多
姐就是有狂的资本
3楼-- · 2019-01-13 20:50

According to nginx documentation

there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else

So you could define something like

location ~ (dir1|file2\.php) { 
    # empty
}

location / {
    rewrite ^/(.*) http://example.com/$1 permanent; 
}
查看更多
手持菜刀,她持情操
4楼-- · 2019-01-13 20:50

Suppose you have two locations say, location1 and location2, you can try following location block configuration to solve your problem.

 location ~ ^/(location1|location2) {
      rewrite (.*) http://example.com/$1 permanent; 
 }

Also the problem you are facing could be because of the sequence of multiple location block in your configuration. Please check, In case any of the location block that comes before this, serves the request.

查看更多
登录 后发表回答