简体   繁体   English

Nginx重定向到www域无法正常工作

[英]Nginx redirect to www domain not working

I have the following nginx configuration. 我有以下nginx配置。

server {
    listen 80;
    listen [::]:80;
    listen 443 ssl;
    server_name example.com;
    return 301 https://www.example.com$request_uri;
}
  • it redirects http://example.com to https://www.example.com 它将http://example.com重定向到https://www.example.com
  • but does not redirect https://example.com to https://www.example.com . 但不会将https://example.com重定向到https://www.example.com

How can I redirect https://example.com to https://www.example.com ? 如何将https://example.com重定向到https://www.example.com

please separate http and https traffic. 请分开http和https流量。 your current config is messing up a bit with things. 你当前的配置搞砸了一些东西。 The following code rewrites all request from http://example.com to https://example.com using a permanent redirect: 以下代码使用永久重定向将所有请求从http://example.com重写为https://example.com

server {
   listen 80;
   server_name example.com;
   return 301 https://$server_name$request_uri;
}

Second code block will handle the request coming in from port 443 (example here will give you an A rating on ssllabs.com): 第二个代码块将处理来自端口443的请求(此处的示例将在ssllabs.com上为您提供A评级):

server {
   listen 443 ssl;
   server_name example.com;

   ssl_certificate /path_to/ssl.crt;
   ssl_certificate_key /path_to/ssl.key;
   ssl_session_timeout 1d;
   ssl_session_cache shared:SSL:10m;
   # ssl_session_tickets off;

   # openssl dhparam -out dhparam.pem 2048
   # ssl_dhparam /etc/nginx/SSL/dhparams.pem;

   ssl_protocols TLSv1.1 TLSv1.2;
   ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGC$
   ssl_prefer_server_ciphers on;

   add_header Strict-Transport-Security "max-age=15768000;includeSubdomains; preload";

   root /srv/wwwroot/;
   index index.html index.htm index.php;

   client_max_body_size 20M;

   location / {
       # your special config if needed
   }


 }

and finally with a third block in our config we rewrite https://www.example.com back to https://example.com : 最后在我们的配置中使用第三个块,我们将https://www.example.com重写为https://example.com

server {
   listen 443;
   server_name www.example.com;
   return 301 https://$server_name$request_uri;
}

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM