基於nginx搭建了一個https訪問的虛擬主機,監聽的域名是test.com,但是很多用戶不清楚https和http的區別,會很容易敲成http://test.com,這時會報出404錯誤,所以我需要做基於test.com域名的http向https的強制跳轉
我總結了三種方式,跟大家共享一下
1.nginx的rewrite方法
思路
配置
1 server { 2 listen 192.168.1.111:80; 3 server_name test.com; 4
5 rewrite ^(.*)$ https://$host$1 permanent;
6 }
搭建此虛擬主機完成后,就可以將http://test.com的請求全部重寫到https://test.com上了
2.nginx的497狀態碼
error code 497
497 - normal request was sent to HTTPS
解釋:當此虛擬站點只允許https訪問時,當用http訪問時nginx會報出497錯誤碼
思路
配置
1 server { 2 listen 192.168.1.11:443; #ssl端口
3 listen 192.168.1.11:80; #用戶習慣用http訪問,加上80,后面通過497狀態碼讓它自動跳到443端口
4 server_name test.com; 5 #為一個server{......}開啟ssl支持
6 ssl on; 7 #指定PEM格式的證書文件
8 ssl_certificate /etc/nginx/test.pem; 9 #指定PEM格式的私鑰文件
10 ssl_certificate_key /etc/nginx/test.key; 11
12 #讓http請求重定向到https請求
13 error_page 497 https://$host$uri?$args;
14 }
3.index.html刷新網頁
思路
index.html
思路
index.html
1 <html>
2 <meta http-equiv="refresh" content="0;url=https://test.com/">
3 </html>
nginx虛擬主機配置
1 server { 2 listen 192.168.1.11:80; 3 server_name test.com; 4 location / { 5 #index.html放在虛擬主機監聽的根目錄下
6 root /srv/www/http.test.com/; 7 } 8 #將404的頁面重定向到https的首頁
9 error_page 404 https://test.com/;
10 }
這應該是大家最容易想到的方法,將所有的http請求通過rewrite重寫到https上即可
利用error_page命令將497狀態碼的鏈接重定向到https://test.com這個域名上
上述兩種方法均會耗費服務器的資源,我們用curl訪問baidu.com試一下,看百度的公司是如何實現baidu.com向www.baidu.com的跳轉
nginx虛擬主機配置

可以看到百度很巧妙的利用meta的刷新作用,將baidu.com跳轉到www.baidu.com.因此我們可以基於http://test.com的虛擬主機路徑下也寫一個index.html,內容就是http向https的跳轉