需求簡(jiǎn)介
基于nginx搭建了一個(gè)https訪問的虛擬主機(jī),監(jiān)聽的域名是test.com,但是很多用戶不清楚https和http的區(qū)別,會(huì)很容易敲成http://test.com,這時(shí)會(huì)報(bào)出404錯(cuò)誤,所以我需要做基于test.com域名的http向https的強(qiáng)制跳轉(zhuǎn)
我總結(jié)了三種方式,跟大家共享一下
nginx的rewrite方法
思路
這應(yīng)該是大家最容易想到的方法,將所有的http請(qǐng)求通過rewrite重寫到https上即可
配置
1
2
3
4
5
6
|
server { listen 111:80; server_name testcom; rewrite ^(*)$ https: // $host$1 permanent; } |
搭建此虛擬主機(jī)完成后,就可以將http://test.com的請(qǐng)求全部重寫到https://test.com上了
nginx的497狀態(tài)碼
error code 497
1
|
497 - normal request was sent to HTTPS |
解釋:當(dāng)此虛擬站點(diǎn)只允許https訪問時(shí),當(dāng)用http訪問時(shí)nginx會(huì)報(bào)出497錯(cuò)誤碼
思路
利用error_page命令將497狀態(tài)碼的鏈接重定向到https://test.com這個(gè)域名上
配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
server { listen 11:443; #ssl端口 listen 11:80; #用戶習(xí)慣用http訪問,加上80,后面通過497狀態(tài)碼讓它自動(dòng)跳到443端口 server_name testcom; #為一個(gè)server{}開啟ssl支持 ssl on; #指定PEM格式的證書文件 ssl_certificate /etc/nginx/testpem ; #指定PEM格式的私鑰文件 ssl_certificate_key /etc/nginx/testkey ; #讓http請(qǐng)求重定向到https請(qǐng)求 error_page 497 https: // $host$uri?$args; } |
index.html刷新網(wǎng)頁
思路
上述兩種方法均會(huì)耗費(fèi)服務(wù)器的資源,我們用curl訪問baidu.com試一下,看百度的公司是如何實(shí)現(xiàn)baidu.com向www.baidu.com的跳轉(zhuǎn)
可以看到百度很巧妙的利用meta的刷新作用,將baidu.com跳轉(zhuǎn)到www.baidu.com.因此我們可以基于http://test.com的虛擬主機(jī)路徑下也寫一個(gè)index.html,內(nèi)容就是http向https的跳轉(zhuǎn)
index.html
1
2
3
|
< html > < meta http-equiv = "refresh" content = "0;url=https://testcom/" > </ html > |
nginx虛擬主機(jī)配置
1
2
3
4
5
6
7
8
9
10
11
|
server { listen 11:80; server_name testcom; location / { #indexhtml放在虛擬主機(jī)監(jiān)聽的根目錄下 root /srv/www/httptestcom/ ; } #將404的頁面重定向到https的首頁 error_page 404 https: //testcom/ ; } |
后記
上述三種方法均可以實(shí)現(xiàn)基于nginx強(qiáng)制將http請(qǐng)求跳轉(zhuǎn)到https請(qǐng)求,大家可以評(píng)價(jià)一下優(yōu)劣或者根據(jù)實(shí)際需求進(jìn)行選擇。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://blog.csdn.net/wzy_1988/article/details/8549290