Using nginx, I want to redirect all subdomains of example.com
to www.example.com
.
I have seen redirects here to redirect non-www to www or vise versa, but I also want www2.site.com blabla.site.com
to be redirected.
I have a wildcard dns for the domain.
For apache this can be done easily with following:
RewriteCond %{HTTP_HOST} !www.example.com [NC]
RewriteRule (.*) http://www.example.com%{REQUEST_URI} [R=301,L]
The below seem to work, but it is not recommended according to the ifisevil page.
if ($http_host !~ "www.site.com"){
rewrite ^(.*)$ http://www.example.com$request_uri redirect;
}
The best way to do this in nginx is with a combination of two server blocks:
I have tested this on my laptop, since you reported it not working. I get the following result locally (after adding
www2.test.localhost
andwww.test.localhost
to my/etc/hosts
, along with the nginx config bit, and reloading nginx):So yes, this definitely works.
References: