我的 nginx 配置如下::
# HTTP - redirect all requests to HTTPS:
server {
listen 80;
listen [::]:80 default_server ipv6only=on;
return 301 https://$host$request_uri;
}
# HTTPS - proxy requests on to local Node.js app:
server {
listen 443;
server_name example.com;
ssl on;
# Use certificate and key provided by Let's Encrypt:
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
# Pass requests for / to localhost:3000:
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://localhost:3000/;
proxy_ssl_session_reuse off;
proxy_set_header Host $http_host;
proxy_cache_bypass $http_upgrade;
proxy_redirect off;
}
}
当前具有上述配置:
http://example.com
重定向至https://example.com
。
当我输入时,http://www.example.com
它会重定向到https://www.example.com
。
我希望www
将请求重定向到non-www
因此,如果有人输入http://www.example.com
或,https://www.example.com
我希望将其重定向到https://example.com
。我该如何实现这一点?
答案1
你需要更换
# HTTP - redirect all requests to HTTPS:
server {
listen 80;
listen [::]:80 default_server ipv6only=on;
return 301 https://$host$request_uri;
}
和:
# HTTP - redirect all requests to HTTPS:
server {
listen 80;
listen [::]:80 default_server ipv6only=on;
return 301 https://example.com$request_uri;
}
这样,nginx 就不会使用Host
客户端请求中的标头来确定重定向的主机。
答案2
这是标准的 Nginx 网站设置,用于转发到非 www https 网站
# Main website, https non-www
server {
server_name example.com;
listen 443 ssl http2; # http2 is optional
# locations, ssl configuration, etc
}
# forward https www to non-www
server {
server_name www.example.com;
listen 443 ssl;
return 301 https://example.com$request_uri;
}
# Forward http to https
server {
listen 80;
server_name example.com www.example.com;
access_log /var/log/nginx/access.log main buffer=128k flush=1m if=$log_ua;
return 301 https://example.com$request_uri;
}