Ngingredirecthttp和https到https://域(没有www)

这是我的Nginxconfiguration:

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; } } 

用这个configuration我可以redirect:

  • http://domain.com – > https://domain.com
  • https://domain.com – > https://domain.com (相同)
  • http://www.domain.com – > https://domain.com
  • https://www.domain.com – >错误

我如何让我的服务器redirecthttps www到https非www。 请记住,我需要使用相同的Nginx服务器(vide server_name)处理多个域。

谢谢!

对于单个域,您可以像这样实现它:

 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; }