views:

1016

answers:

3

I see the Nginx HttpRewriteModule documentation has an example to rewrite a www-prefixed domain to a non-www-prefixed domain:

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

How can I do the reverse-- rewrite a non-www-prefixed domain to a www-prefixed domain? I thought maybe I could do something like the following but Nginx doesn't like the nested if statement.

if ($host !~* ^www\.) {                       # check if host doesn't start with www.
    if ($host ~* ([a-z0-9]+\.[a-z0-9]+)) {    # check host is of the form xxx.xxx (i.e. no subdomain)
        set $host_with_www www.$1;
        rewrite ^(.*)$ http://$host_with_www$1 permanent;
    }
}

Also I wanted this to work for any domain name without explicitly telling Nginx to rewrite domain1.com -> www.domain1.com, domain2.com -> www.domain2.com, etc. since I have a large number of domains to rewrite.

+2  A: 

Well I guess I don't really need the outer "if" statement since I'm only checking for domains of the form xxx.xxx anyways. The following works for me, though it's not robust. Let me know if there is a better solution.

    if ($host ~* ^([a-z0-9\-]+\.(com|net|org))$) {
        set $host_with_www www.$1;
        rewrite ^(.*)$ http://$host_with_www$1 permanent;
    }

Edit: Added hyphen to the regular expression since it is a valid character in a hostname.

saltycrane
A: 
if ($host !~* ^www\.) {
    rewrite ^(.*)$ http://www.$host$1 permanent;
}
ss
This doesn't work for me because I don't want to rewrite subdomains like static.mydomain.com. I probably should have stated that in my question. Thanks for your answer.
saltycrane
A: 
if ($host ~* ^[^.]+\.[^.]+$) {
    rewrite ^(.*)$ http://www.$host$1 permanent;
}

It's only possible to get valid hostnames because the request will never make it to your server otherwise, so there's no need to build your own validation logic.

Anthony DiSanti