Nginx – Simple nginx server_name regex does not find match

nginxregex

I have an nginx box running version 1.8.1 on AWS. I am converting numerous DNS routing conditions into nginx and have encountered many DNS entries where *.yet_another_domain.* would be useful, but nginx does not appear to like having wildcards on both sides of the host (that "or" in the documentation, referring to which side a wildcard can go, can be a loaded word to software developers). Therefore, I moved on to regular expressions.

I have set up a hosts entry on my localhost for both uno.com and www.uno.com, pointing them to my nginx box. Using server_name values such as www.uno.com uno.com or .uno.com gives me results, so I know nginx is capable of hitting my configuration when I don't rely on regular expressions (*.uno.com is another matter, having some flaws, but I digress). I've tried a number of regular expressions, all without nginx matching to either uno.com or www.uno.com.

Some regular expressions I have tried:

server_name ~^(.*\.?uno\..*)$; (hoping to match www.uno.com and uno.com)

server_name ~^(.*\.)?uno\.com$; (also looking for www.uno.com and uno.com)

server_name ~uno\.com; (just looking for uno.com anywhere in the host)

server_name ~^uno.*; (looking for a host starting with uno)

My AWS nginx instance returns a nifty nginx/Amazon test page whenever I look for uno.com or www.uno.com when using any of these regular expressions, but not the hard-coded return value I am looking for.

Best Answer

So here is the problem. I have an include in my nginx.conf for a directory in which I have multiple other .conf files. In one of the other files, there was a server_name for *.com. According to nginx's rules for handling requests, wildcard server_names have higher priority than regular expression server_names. Now, this was actually something I was aware of -- what really caught me was that, in the event that no valid locations were discovered, nginx apparently does not go back to find other possible server_name matches. Drat.

And here is a nice, detailed description of nginx's request resolution process, that helped me to realize that it wasn't going to go looking for other server_name matches as I'd hoped:

https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms

Related Topic