如何在 CentOS 上的 Nginx 中將子網域重新導向到根域?

如何在 CentOS 上的 Nginx 中將子網域重新導向到根域?

我將 Centos 與 Nginx 和 Puma 一起使用。我想將所有子網域重定向到我的主根域,因此我按照此處的說明進行操作 -https://stackoverflow.com/questions/26801479/nginx-redirect-all-subdomains-to-main-domain。但是我無法讓它工作。下面是我的配置

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;
  }
}

如果我排除「return 301http://mydomein.com$request_uri;" 行,那麼我的網站將在根網域上運行,但不能在任何子網域上運行(例如,查看子網域將產生預設的Nginx 索引頁)。如何將所有子網域重新導向到我的主域並保留我的 Rails/Puma 配置?

答案1

您目前正在頂級網域虛擬主機上偵聽重定向。您需要做的是有一個單獨的虛擬主機偵聽器,可以重定向到頂點。這是重定向到頂點域定義的通配符偵聽器的範例:

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;
  }
}

相關內容