![如何在 CentOS 上的 Nginx 中将子域名重定向到根域名?](https://linux22.com/image/718328/%E5%A6%82%E4%BD%95%E5%9C%A8%20CentOS%20%E4%B8%8A%E7%9A%84%20Nginx%20%E4%B8%AD%E5%B0%86%E5%AD%90%E5%9F%9F%E5%90%8D%E9%87%8D%E5%AE%9A%E5%90%91%E5%88%B0%E6%A0%B9%E5%9F%9F%E5%90%8D%EF%BC%9F.png)
我使用的是 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;
}
}
如果我排除“返回 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;
}
}