Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excluding directory from regex redirect

Tags:

I wish to redirect all URLs with underscores to their dashed equivalent.

E.g. /nederland/amsterdam/car_rental becomes /nederland/amsterdam/car-rental. For this I'm using the technique described here: How to replace underscore to dash with Nginx. So my location block is matched to:

location ~ (_) 

But I only want to do this on URLs not in the /admin namespace. To accomplish this I tried combining the regex with a negative lookup: Regular expression to match a line that doesn't contain a word?. The location now matches with:

(?=^(?!\/admin))(?=([^_]*))

Rubular reports the string /nederland/amsterdam/car_rental to match the regex, while /admin/stats_dashboard is not matched, just as I want it. However when I apply this rule to the nginx config, the site ends up in redirect loops. Is there anything I've overlooked?

UPDATE: I don't actually want to rewrite anything in the /admin namespace. The underscore-to-dash rewrite should only take place on all URLs not in the /admin namespace.

like image 601
richard Avatar asked Aug 11 '15 09:08

richard


1 Answers

The Nginx location matching order is such that locations defined using regular expressions are checked in the order of their appearance in the configuration file and the search of regular expressions terminates on the first match.

With this knowledge, in your shoes, I will simply define one location using a regular expression for "admin" above that for the underscores you got from the Stack Overflow Answer you linked to.

location ~ (\badmin\b) {
    # Config to process urls containing "admin"
}
location ~ (_) {
    # Config to process urls containing "_"
}

Any request with admin in it will be processed by the first location block no matter whether it has an underscore or not because the matching location block appears before that for the underscores.

** PS **

As another answer posted by cnst a couple of days after mine shows, the link to the documentation on the location matching order I posted also indicates that you may also use the ^~modifier to match the /admin folder and skip the location block for the underscores.

I personally tend not to use this modifier and prefer to band regex based locations together with annotated comments but it is certainly an option.

However, you will need to be careful, depending on your setup, as requests starting with "/admin", but longer, may be matching with the modifier and lead to unexpected results.

As said, I prefer my regex based approach safe in the knowledge that no one will start to arbitrarily change the order of things in the config file without a clear understanding.

like image 172
Dayo Avatar answered Sep 17 '22 12:09

Dayo