nginx subdomain rewrite

Whats the significance of the extra period before domain.com? Is the goal to remove the www from the URL? If so, this should do the trick:

if ($host ~* www\.(.*)) {
  set $host_without_www $1;
  rewrite ^(.*)$ http://$host_without_www$1 permanent; # $1 contains '/foo', not 'www.mydomain.com/foo'
}

Don't forget to: sudo /etc/init.d/nginx restart to load it up

Source: NGINX Wiki


That's quite a bit of a hack.

The fastest way performance wise would be

server {
  server_name www.domain.com;
  rewrite ^ http://domain.com$request_uri permanent;
}

You save a regex match as well as two captures plus you get the advantage of nginx using hash tables to look up the matching server block.

Also, you do not need to restart nginx - a reload is all that's required, and whoever would want to have more down time than required?


You can use regular expression server names (see http://nginx.org/en/docs/http/server_names.html#regex_names):

server {
  listen 80;
  listen 443;
  server_name ~^www\.(\w+)\.domain\.com$
  location / {
    rewrite ^ $scheme://$1.domain.com$request_uri permanent;
  }
}

Martin F's solution is all well and good, until you've got hundreds of domains. I would, however, suggest going the other way - serve the app at www.joe.domain.com, and redirect from joe.domain.com. Pretty sure that's in an RFC.