Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 '' 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:                          (stays)                              (goes to)                  (stays the same)                     (no uri, goes to)             (goes to)         (goes to)

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$city/prelaunch/$args permanent;
  rewrite (.*)$uri$args permanent;
share|improve this question

This is best accomplished using three servers:

#, actually serves content
server {
  root /doc/root;

  # locations, etc

# redirect ->
server {
  rewrite ^$request_uri? permanent;

# handle 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 ^$city/prelaunch; }
  location = /landing { rewrite ^$city/prelaunch; }
  # should there be a /$city before $request_uri?
  location / { rewrite ^$request_uri?; }
share|improve this answer
Thanks, this is really helpful. Our cloud host is on nginx 0.7.65, however, so the references to '$city' is unrecognized. Is there a way to keep the definitions in the server defs like your example, but add a variable in a way the back release supports? – user85836 Jun 28 '11 at 1:25
I edited the config to show how you would set $city pre-0.8.25 – kolbyjack Jun 28 '11 at 12:30
Thank you! I will be trying tonight. – user85836 Jun 28 '11 at 19:04
Works perfectly! Thank you. – user85836 Jun 29 '11 at 20:36
Could you accept my answer, then? – kolbyjack Jun 30 '11 at 16:24

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.