Nginx – How to redirect subdomains to the root domain in Nginx on CentOS

centosdomainnginxredirectsubdomain

I'm using Centos with Nginx and Puma. I would like to redirect all subdomains to my main root domain, so I was following the instructions here — https://stackoverflow.com/questions/26801479/nginx-redirect-all-subdomains-to-main-domain . However I can't get it to work. Below is my configuration

upstream projecta {
  server unix:///home/rails/projecta_production/shared/sockets/puma.sock;
}

server {
  listen 80;
  server_name mydomein.com;
  return 301 http://mydomein.com$request_uri;
  root /home/rails/projecta_production/public; # I assume your app is located at this location

  location / {
    proxy_pass http://projecta; # match the name of upstream directive which is defined above
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }

  location ~* ^/assets/ {
    # Per RFC2616 - 1 year maximum expiry
    expires 1y;
    add_header Cache-Control public;

    # Some browsers still send conditional-GET requests if there's a
    # Last-Modified header or an ETag header even if they haven't
    # reached the expiry date sent in the Expires header.
    add_header Last-Modified "";
    add_header ETag "";
    break;
  }
}

If I exclude the "return 301 http://mydomein.com$request_uri;" line then my site will work on the root domain ,but not on any of the sub-domains (e.g. viewing a subdomain will yield the default Nginx index page). How do I redirect all sub-domains to my main domain and preserve my Rails/Puma configuration?

Best Answer

You are currently listening on the apex domain vhost for the redirect. What you need to do is have a separate vhost listener that redirects to the apex. This is an example of a wildcard listener redirecting to the apex domain definition:

upstream projecta {
  server unix:///home/rails/projecta_production/shared/sockets/puma.sock;
}

# Listener for all subdomains
server {
  listen 80;
  server_name *.mydomein.com;
  # If you want to redirect all requests, not just subdomains, use below config instead.
  # server_name _;
  return 301 http://mydomein.com$request_uri;
}

# Listener for Apex Domain
server {
  listen 80;
  server_name mydomein.com;
  root /home/rails/projecta_production/public; # I assume your app is located at this location

  location / {
    proxy_pass http://projecta; # match the name of upstream directive which is defined above
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }

  location ~* ^/assets/ {
    # Per RFC2616 - 1 year maximum expiry
    expires 1y;
    add_header Cache-Control public;

    # Some browsers still send conditional-GET requests if there's a
    # Last-Modified header or an ETag header even if they haven't
    # reached the expiry date sent in the Expires header.
    add_header Last-Modified "";
    add_header ETag "";
    break;
  }
}