nginx rewrite rule for using domain host to redirect to specific internal directory

Posted by user85836 on Server Fault See other posts from Server Fault or by user85836
Published on 2011-06-27T16:01:50Z Indexed on 2011/06/27 16:25 UTC
Read the original article Hit count: 274

Filed under:
|

I'm new to Nginx rewrites and looking for help in getting a working and minimal rewrite code. We would like to use urls like 'somecity.domain.com' on campaign materials and have the result go to city-specific content within the 'www' site.

So, here are use cases, if the customer enters:

www.domain.com                          (stays) www.domain.com
domain.com                              (goes to) www.domain.com
www.domain.com/someuri                  (stays the same)
somecity.domain.com                     (no uri, goes to) www.domain.com/somecity/prelaunch
somecity.domain.com/landing             (goes to)   www.domain.com/somecity/prelaunch
somecity.domain.com/anyotheruri         (goes to) www.domain.com/anyotheruri

Here's what I've come up with so far, and it partially works. What I can't understand is how to check if there is no path/uri after the host, and I'm guessing there is probably a way better way to do this.

if ($host ~* ^(.*?)\.domain\.com)
{   set $city $1;}
if ($city ~* www)
{   break; }
if ($city !~* www)
{ 
  rewrite ^/landing http://www.domain.com/$city/prelaunch/$args permanent;
  rewrite (.*) http://www.domain.com$uri$args permanent;
}

© Server Fault or respective owner

Related posts about nginx

Related posts about rewrite