这是我的 Nginx 配置:
upstream app_server {
# Bindings to the Gunicorn server
server 127.0.0.1:8002 fail_timeout=0;
}
server {
listen 80;
server_name "~^www\.(.*)$";
return 301 https://$host$request_uri;
}
server {
access_log path_to_nginx-access.log;
error_log path_to_nginx-error.log;
listen 443 ssl;
server_name _;
ssl_certificate path_to_nginx.crt;
ssl_certificate_key path_to_nginx.key;
client_max_body_size 4G;
keepalive_timeout 5;
root path_to_root;
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $host;
proxy_redirect off;
if (!-f $request_filename) {
proxy_pass http://app_server;
break;
}
}
error_page 500 502 503 504 /500.html;
location = /500.html {
root path_to_templates;
}
}
通过此配置我可以重定向:
- http://域名.com->https://domain.com
- https://domain.com->https://domain.com(相同的)
- http://www.domain.com->https://domain.com
- https://www.domain.com-> 错误
如何让我的服务器将 https www 重定向到 https 非 www。请记住,我需要使用同一个 Nginx 服务器(参见 server_name)处理多个域。
谢谢!
答案1
对于单个域,您可以像这样实现:
server {
listen 443;
server_name www.domain.com;
ssl_certificate path_to_certificate;
ssl_certificate_key path_to_key;
return 301 https://domain.com$request_uri;
}