nginx www redirect to non-www with subdomain

2019-07-10 04:54发布

问题:

How can i redirect from www to non www for this rule ~^(?\w+).example.com ?

server {
    listen 80;
    listen [::]:80 ipv6only=on;
    server_name ~^(?<subdomain>\w+)\.example\.com$;
}

I try separate main domain redirect and all subdomains redirect but have recursive redirection for main domain.

server {
    server_name www.example.com;
    return 301 $scheme://example.com$request_uri;
}

server {
     server_name "~^www\.(.*)$" ;
     return 301 $scheme://$1$request_uri ;
}

Then i try only

server {
     server_name "~^www\.(.*)$" ;
     return 301 $scheme://$1$request_uri ;
}

and that work for subdomains. But in main domain i have redirect for $request_uri without domain.

回答1:

One thing to remember is that if nginx cannot find a matching server_name it will use the default server. And unless you define a default_server, it will use the first server block listening on the appropriate port. See this document for details.

Clearly example.com does not match the regular expression ~^(?<subdomain>\w+)\.example\.com$, however, your current server block works because it is the implicit default server.

Regular expression server blocks are evaluated in order, so place the www. rule first so that www.example.com is not treated as a subdomain.

Make the main server block default explicitly so that it continues to handle example.com.

server {
    server_name "~^www\.(.*)$" ;
    return 301 $scheme://$1$request_uri ;
}
server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;
    server_name ~^(?<subdomain>\w+)\.example\.com$;
    ...
}