nginx強制使用https訪問(http跳轉到https)
需求簡介
基於nginx搭建了一個https訪問的虛擬主機,監聽的域名是test.com,但是很多使用者不清楚https和http的區別,會很容易敲成http://test.com,這時會報出404錯誤,所以我需要做基於test.com域名的http向https的強制跳轉
我總結了三種方式,跟大家共享一下
nginx的rewrite方法
思路
這應該是大家最容易想到的方法,將所有的http請求通過rewrite重寫到https上即可
配置
server {
listen192.168.1.111:80;
server_nametest.com;
rewrite ^(.*)$https://$host$1permanent;
}
搭建此虛擬主機完成後,就可以將http://test.com的請求全部重寫到https://test.com上了
nginx的497狀態碼
error code 497
497 - normal request was sent to HTTPS
解釋:當此虛擬站點只允許https訪問時,當用http訪問時nginx會報出497錯誤碼
思路
利用error_page命令將497狀態碼的連結重定向到https://test.com這個域名上
配置
server {
listen 192.168.1.11:443;#ssl埠
listen 192.168.1.11:80;#使用者習慣用http訪問,加上80,後面通過497狀態碼讓它自動跳到443埠
server_name test.com;
#為一個server{......}開啟ssl支援
ssl on;
#指定PEM格式的證書檔案
ssl_certificate /etc/nginx/test.pem;
#指定PEM格式的私鑰檔案
ssl_certificate_key /etc/nginx/test.key;
#讓http請求重定向到https請求
error_page 497https://$host$uri?$args;
}
index.html重新整理網頁
思路
上述兩種方法均會耗費伺服器的資源,我們用curl訪問baidu.com試一下,看百度的公司是如何實現baidu.com向www.baidu.com的跳轉
可以看到百度很巧妙的利用meta的重新整理作用,將baidu.com跳轉到www.baidu.com.因此我們可以基於http://test.com的虛擬主機路徑下也寫一個index.html,內容就是http向https的跳轉
index.html
<html>
<meta http-equiv="refresh" content="0;url=https://test.com/">
</html>
nginx虛擬主機配置
server {
listen 192.168.1.11:80;
server_nametest.com;
location / {
#index.html放在虛擬主機監聽的根目錄下
root /srv/www/http.test.com/;
}
#將404的頁面重定向到https的首頁
error_page404https://test.com/;
}
後記
(1)上述三種方法均可以實現基於nginx強制將http請求跳轉到https請求,大家可以評價一下優劣或者根據實際需求進行選擇。
需求簡介
基於nginx搭建了一個https訪問的虛擬主機,監聽的域名是test.com,但是很多使用者不清楚https和http的區別,會很容易敲成http://test.com,這時會報出404錯誤,所以我需要做基於test.com域名的http向https的強制跳轉
我總結了三種方式,跟大家共享一下
nginx的rewrite方法
思路
這應該是大家最容易想到的方法,將所有的http請求通過rewrite重寫到https上即可配置
- server{
- listen192.168.1.111:80;
- server_nametest.com;
- rewrite^(.*)$https://$host$1permanent;
- }
搭建此虛擬主機完成後,就可以將http://test.com的請求全部重寫到https://test.com上了
nginx的497狀態碼
error code 497
- 497-normalrequestwassenttoHTTPS
解釋:當此虛擬站點只允許https訪問時,當用http訪問時nginx會報出497錯誤碼
思路
利用error_page命令將497狀態碼的連結重定向到https://test.com這個域名上配置
- server{
- listen192.168.1.11:443;#ssl埠
- listen192.168.1.11:80;#使用者習慣用http訪問,加上80,後面通過497狀態碼讓它自動跳到443埠
- server_nametest.com;
- #為一個server{......}開啟ssl支援
- sslon;
- #指定PEM格式的證書檔案
- ssl_certificate/etc/nginx/test.pem;
- #指定PEM格式的私鑰檔案
- ssl_certificate_key/etc/nginx/test.key;
- #讓http請求重定向到https請求
- error_page497https://$host$uri?$args;
- }
index.html重新整理網頁
思路
上述兩種方法均會耗費伺服器的資源,我們用curl訪問baidu.com試一下,看百度的公司是如何實現baidu.com向www.baidu.com的跳轉 可以看到百度很巧妙的利用meta的重新整理作用,將baidu.com跳轉到www.baidu.com.因此我們可以基於http://test.com的虛擬主機路徑下也寫一個index.html,內容就是http向https的跳轉index.html
- <html>
- <metahttp-equiv="refresh"content="0;url=https://test.com/">
- </html>
nginx虛擬主機配置
- server{
- listen192.168.1.11:80;
- server_nametest.com;
- location/{
- #index.html放在虛擬主機監聽的根目錄下
- root/srv/www/http.test.com/;
- }
- #將404的頁面重定向到https的首頁
- error_page404https://test.com/;
- }