nginx rewrite rule for using domain host to redirect to specific internal directory
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;
}
This is best accomplished using three servers:
# www.domain.com, actually serves content
server {
server_name www.domain.com;
root /doc/root;
# locations, etc
}
# redirect domain.com -> www.domain.com
server {
server_name domain.com;
rewrite ^ http://www.domain.com$request_uri? permanent;
}
# handle anything.domain.com that wasn't handled by the above servers
server {
# ~ means regex server name
# 0.8.25+
#server_name ~(?<city>.*)\.domain\.com$;
# < 0.8.25
server_name ~(.*)\.domain\.com$;
set $city $1;
location = / { rewrite ^ http://www.domain.com/$city/prelaunch; }
location = /landing { rewrite ^ http://www.domain.com/$city/prelaunch; }
# should there be a /$city before $request_uri?
location / { rewrite ^ http://www.domain.com$request_uri?; }
}