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.
One thing to remember is that if
nginx
cannot find a matchingserver_name
it will use the default server. And unless you define adefault_server
, it will use the firstserver
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 currentserver
block works because it is the implicit default server.Regular expression
server
blocks are evaluated in order, so place thewww.
rule first so thatwww.example.com
is not treated as a subdomain.Make the main
server
block default explicitly so that it continues to handleexample.com
.