Nginx location "not equal to" regex

RegexNginxWebserver

Regex Problem Overview


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.

Regex Solutions


Solution 1 - Regex

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; 
}

Solution 2 - Regex

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

Explanation of Regex :

If URL does not match any of the following path

example.com/favicon.ico
example.com/resources
example.com/robots.txt

Then it will go inside that location block and will process it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChristiaanView Question on Stackoverflow
Solution 1 - RegexDéjà vuView Answer on Stackoverflow
Solution 2 - Regexuser1642018View Answer on Stackoverflow