Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx rewrite all wildcard subdomains to www.site.com [closed]

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;
}
like image 651
user2143308 Avatar asked Mar 07 '13 08:03

user2143308


2 Answers

The best way to do this in nginx is with a combination of two server blocks:

server {
  server_name *.example.org;
  return 301 $scheme://example.org$request_uri;
}

server {
  server_name www.example.org;

  #add in further directives to serve your content
}

I have tested this on my laptop, since you reported it not working. I get the following result locally (after adding www2.test.localhost and www.test.localhost to my /etc/hosts, along with the nginx config bit, and reloading nginx):

$ curl --head www2.test.localhost
HTTP/1.1 301 Moved Permanently
Server: nginx/1.2.6
Date: Thu, 07 Mar 2013 12:29:32 GMT
Content-Type: text/html
Content-Length: 184
Connection: keep-alive
Location: http://www.test.localhost/

So yes, this definitely works.

like image 106
cobaco Avatar answered Oct 30 '22 05:10

cobaco


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

server {
    server_name www.example.com;
    [...]
}

References:

  • http://nginx.org/en/docs/http/server_names.html
  • http://nginx.org/en/docs/http/converting_rewrite_rules.html
  • http://nginx.org/r/server_name
  • http://nginx.org/r/return
like image 13
VBart Avatar answered Oct 30 '22 06:10

VBart