站點默認訪問https


需求簡介

 現在網站都是https訪問了,再用http會顯得很low,所以我要把網站設置為默認的https訪問。  

1nginx的rewrite方法 

這應該是大家最容易想到的方法,將所有的http請求通過rewrite重寫到https上即可

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

 

2nginx的497狀態碼

error code 497

497 - normal request was sent to HTTPS


 當此虛擬站點只允許https訪問時,當用http訪問時nginx會報出497錯誤碼
 
利用error_page命令將497狀態碼的鏈接重定向到https://localhost這個域名上
 
server {
 
  listen 192.168.1.11:443;    #ssl端口
 
  listen 192.168.1.11:80;    #用戶習慣用http訪問,加上80,后面通過497狀態碼讓它自動跳到443端口
 
   server_name chaogg.com;
 
   #為一個server{......}開啟ssl支持
 
   ssl on;
 
   #指定PEM格式的證書文件
 
   ssl_certificate /etc/nginx/chaogg.pem;
 
   #指定PEM格式的私鑰文件
 
   ssl_certificate_key /etc/nginx/chaogg.key; 
 
 
   #讓http請求重定向到https請求
 
    error_page 497    https://$host$uri?$args;
}

 

3index.html刷新網頁 

上述兩種方法均會耗費服務器的資源,我們用curl訪問baidu.com試一下,看百度的公司是如何實現baidu.com向www.baidu.com的跳轉
 
 
可以看到百度很巧妙的利用meta的刷新作用,將baidu.com跳轉到www.baidu.com.因此我們可以基於http://chaogg.com的虛擬主機路徑下也寫一個index.html,內容就是http向https的跳轉 

index.html

 
<html>
 
<meta http-equiv="refresh" content="0;url=https://chaogg.com/">
 
</html>

 

nginx虛擬主機配置

 
 
server {
 
listen 192.168.1.11:80;
 
server_name    chaogg.com; 
 
 
location / {
 
#index.html放在虛擬主機監聽的根目錄下
 
root /srv/www/http.chaogg.com/;
 
}
 
#將404的頁面重定向到https的首頁
 
error_page    404    https://chaogg.com/;
 
}
 

 

上述三種方法均可以實現基於nginx強制將http請求跳轉到https請求,請放心使用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM