Ubuntu
如何使用反向代理將所有請求正確重定向到 nginx 內的非 www
我有一個由 nginx 內部的反向代理服務的反應網站。最重要的是,我有 SSL。Certbot 正在處理從 http 到 https 的重定向。我還想設置從 www 到非 www 的重定向。我想知道這樣做的正確方法是什麼?
我的配置如下所示:
server { server_name example.com www.example.com; location / { proxy_pass http://localhost:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto http; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-Host $remote_addr; proxy_cache_bypass $http_upgrade; proxy_hide_header X-Powered-By; add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always; add_header X-Frame-Options "SAMEORIGIN" always; add_header X-XSS-Protection "1; mode=block" always; add_header X-Content-Type-Options "nosniff" always; add_header Referrer-Policy "origin-when-cross-origin" always; } error_page 502 /index.html; location /index.html { root /var/www/subdomains/service; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = example.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = www.example.com) { return 301 https://example.com$request_uri; } server_name example.com; listen 80; return 404; # managed by Certbot }
請注意,兩個頁面(www 和非 www)目前都在工作。我只是想避免重複連結,所以我只想要非 www 版本。
將您的 SSL 伺服器塊分成兩部分:
server { server_name www.example.com; listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot return 301 https://example.com$request_uri; } server { server_name example.com; ... # your main config here }