Redirect www to no-www with variable (for multiple domains)?

According to http://wiki.nginx.org/Pitfalls#Server_Name this is the best
solution to redirect www to no-www for one domain:

server {
server_name www.domain.com;
return 301 $scheme://domain.com$request_uri;
}
server {
server_name domain.com;
[…]
}

Is there a way to do this with regex or variables? I’ve ~15 domains and
it
would be more convenient to have only one entry “to rule them all” :wink:

Posted at Nginx Forum:
http://forum.nginx.org/read.php?2,240622,240622#msg-240622

On 7 Jul 2013 10:30, “lennart” [email protected] wrote:

[…]
}

Is there a way to do this with regex or variables? I’ve ~15 domains and it
would be more convenient to have only one entry “to rule them all” :wink:

Absolutely there are ways to do this all in one go. Have a try and let
us
know where you get stuck :slight_smile:

Jonathan

Jonathan M. Wrote:

server {
let us
know where you get stuck :slight_smile:

Jonathan


As a newbie to NGINX (used 10yrs APACHE before) i don’t know the exact
route
on the wiki & forum ;-). I also not found a newbie-section :wink: But off
course, i shall post the solution.

Sajan tells about $host, i’ll give it a try

Posted at Nginx Forum:
http://forum.nginx.org/read.php?2,240622,240625#msg-240625

I should correct my server_name line. It should not have the variable,
but the actual domain names. So I guess you’ll still have to come back
and add each domain.

Sorry. On phone.

Sajan P.

Haven’t testing this, but would you not be able to replace ‘domain.com
with $host?

server {
server_name www.$host;
rewrite ^(.*) $scheme://$host$request_uri permanent;
}

That should work I think. Right now, I do it the way you’ve descrived
individually in all my .conf files for each domain.

  • Sajan P.

On Sun, Jul 7, 2013 at 6:30 PM, lennart [email protected] wrote:

Is there a way to do this with regex or variables? I’ve ~15 domains and it
would be more convenient to have only one entry “to rule them all” :wink:

the regex way, which is supposedly slower:

server {
server_name ~^www.(?.+)$;
listen 80; listen [::]:80;
return 301 $scheme://$domain$request_uri;
}


O< ascii ribbon campaign - stop html mail - www.asciiribbon.org

Edho A. Wrote:

server {
[email protected]
http://mailman.nginx.org/mailman/listinfo/nginx

‘supposedly slower’ is a very good argument to not use RegEx :wink: Do you
have
a source for that?

Posted at Nginx Forum:
http://forum.nginx.org/read.php?2,240622,240679#msg-240679