8

Yet another nginx rewrite rule question

How can I do a rewrite from http://www.*.domain.com to http://*.domain.com ?

thanks in advance

-- Deb

EDIT:

I'm sorry I didn't see the textile formatting removed the * from my question. I fixed it now. What I need to do is go from www.joe.domain.com to joe.domain.com, where joe could be any word.

deb
  • 245
  • 1
  • 4
  • 7

4 Answers4

13

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?

Martin Fjordvald
  • 7,749
  • 1
  • 30
  • 35
7

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

iainlbc
  • 2,694
  • 19
  • 19
  • I'm sorry I didn't see the textile formatting removed the * from my question. What I need to do is go from www.joe.domain.com to joe.domain.com, where joe could be any word. In so you are right, I just need to remove the www. – deb May 08 '10 at 13:38
6

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;
  }
}
blueyed
  • 773
  • 8
  • 13
1

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.

  • If you have nginx handle that many domains then write a script to generate the configuration. It's a fairly straight forward configuration language and you really don't want to do regex parsing on every page load on a high traffic server. – Martin Fjordvald May 08 '10 at 19:16
  • In principle, perhaps, but have you profiled it? I've had some very high load sites using regex for all requests. It takes care. Also, many shared hosting environments don't have serious performance concerns, but do have management overhead concerns. Both solutions could work well within different paramaters. – Justin Alan Ryan May 08 '10 at 19:21
  • If you have hundreds of domains, use regexp in server_name: http://stackoverflow.com/questions/2498712/nginx-subdomain-rewrite – Alexander Azarov May 13 '10 at 07:34