Nginx

Nginx 如何通過單個重定向將 HTTP 非 www 重定向到 HTTPS www?

  • July 3, 2019

我將埠 80 上的傳入 HTTP 流量重定向到埠 443 上的 HTTPS。在那裡,我將非 www 重定向到 www:

http://example.com -> https://example.com –> https://www.example.com

Google pagespeed 洞察力似乎將此視為“多次重定向”。它似乎也確實在每個重定向之間引入了 300-400 毫秒的延遲。

有沒有辦法在所有場景中一步完成重定向?

  1. HTTP 非 www -> HTTPS www
  2. HTTP www -> HTTPS www
  3. HTTPS 非 www -> HTTPS www
  4. HTTPS www -> HTTPS www

我的配置文件如下:

server {
       listen 80;
       server_name example.com;
       rewrite ^/(.*) https://example.com/$1 permanent;
}

server {
       root /var/www/html;

       index index.php index.js index.html index.htm index.nginx-debian.html;

       server_name example.com;
       return 301 https://www.example.com$request_uri;
       ssl_certificate /ssl/example.com.chained.crt;
       ssl_certificate_key /ssl/example.com.key;

       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_cache_bypass $http_upgrade;
       }

       location /wordpress {
       proxy_pass http://localhost:8090;
       proxy_http_version 1.1;
       proxy_set_header X-Forwarded-Proto $scheme;
       proxy_set_header Upgrade $http_upgrade;
       proxy_set_header Connection 'upgrade';
       proxy_set_header Host $host;
       proxy_cache_bypass $http_upgrade;
       }
}

server {
       listen 443 ssl;
       listen [::]:443 ssl;

       root /var/www/html;

       index index.php index.js index.html index.htm index.nginx-debian.html;

       server_name www.example.com;
       ssl_certificate /ssl/example.com.chained.crt;
       ssl_certificate_key /ssl/example.com.key;

       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_cache_bypass $http_upgrade;
       }

       location /wordpress {
       proxy_pass http://localhost:8090;
       proxy_http_version 1.1;
       proxy_set_header X-Forwarded-Proto $scheme;
       proxy_set_header Upgrade $http_upgrade;
       proxy_set_header Connection 'upgrade';
       proxy_set_header Host $host;
       proxy_cache_bypass $http_upgrade;
       }
}

在這部分配置中,您可以:

所有重定向配置範例:

server {
       listen 80;
       server_name example.com  www.example.com;
       rewrite ^/(.*) https://www.example.com/$1 permanent;
}

server {
   listen 443 ssl;
   listen [::]:443 ssl;

   server_name example.com;
   ssl_certificate /ssl/example.com.chained.crt;
   ssl_certificate_key /ssl/example.com.key;
   rewrite ^/(.*) https://www.example.com/$1 permanent;
}


server {
   listen 443 ssl;
   listen [::]:443 ssl;

   server_name www.example.com ;

   # HERE you push all you configuration for HTTPS://WWW.EXAMPLE.COM

   #.../.../

}

引用自:https://serverfault.com/questions/973773