
私は 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;
}
}
「301を返す」を除外するとマイドーム「$request_uri;」行を追加すると、サイトはルート ドメインでは機能しますが、サブドメインでは機能しません (たとえば、サブドメインを表示すると、デフォルトの Nginx インデックス ページが表示されます)。すべてのサブドメインをメイン ドメインにリダイレクトし、Rails/Puma 構成を維持するにはどうすればよいでしょうか。
答え1
現在、リダイレクトのために apex ドメイン vhost をリッスンしています。必要なのは、apex にリダイレクトする別の vhost リスナーを用意することです。これは、apex ドメイン定義にリダイレクトするワイルドカード リスナーの例です。
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;
}
}