Nginx

帶有 SSL 連接錯誤的 Nginx

  • March 1, 2017

我正在嘗試將站點從 HTTP 遷移到 HTTPS,但是,我的 nginx(版本:1.10.3)配置似乎無法正常工作。

需要以下行為:

  • http://www.example.com/path/to/content應該重定向到https://example.com/path/to/content
  • http://example.com/path/to/content應該重定向到https://example.com/path/to/content
  • https://www.example.com/path/to/content應該重定向到https://example.com/path/to/content

使用我目前的配置瀏覽器不會使用 HTTPS 連接到該站點:

server {
   listen 80;
   listen [::]:80;

   server_name www.example.com example.com;

   # redirects both www and non-www to https
   rewrite ^(.*) https://www.example.com$1 permanent;
}

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

   server_name example.com;

   # redirects non-www to www
   rewrite ^(.*) https://www.example.com$1 permanent;
}

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

   include snippets/ssl-example.com.conf;
   include snippets/ssl-params.conf;

   charset utf-8;

   # rest of my config
}
  • 我必須改變什麼才能實現上述行為?
  • 是否可以在第一步中接受(然後重定向)HTTP 請求以保持頁面“活動”並讓我對其進行測試?
  • 我的網站有很好的 SEO 排名(索引為“ http://www.example.com ”),所以正確重定向是必須的。

此配置滿足您的要求:

server {
   listen 80;
   listen [::]:80;

   server_name www.example.com example.com;

   # redirects both www and non-www to https
   return 301 https://example.com$request_uri;
}

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

   server_name www.example.com;

   include snippets/ssl-example.com.conf;
   include snippets/ssl-params.conf;

   # redirects www to non-www
   return 301 https://example.com$request_uri;
}

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

   server_name example.com;

   include snippets/ssl-example.com.conf;
   include snippets/ssl-params.conf;

   charset utf-8;

   # rest of my config
}

我改為rewritereturn因為這樣更有效率。必須使用return一個$request_uri來獲取請求路徑和參數到重定向 URL。

然後我更改了server_name example.com;withlisten 443;塊以提供站點的實際內容,並server_name www.example.com;進行listen 443;重定向。

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