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

According to Pitfalls and Common Mistakes | NGINX 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:

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:

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]
nginx Info Page

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

Posted at Nginx Forum: