nginx配置http強制跳轉https
阿新 • • 發佈:2020-12-04
nginx配置http強制跳轉https
shu_ke 0.0232018.10.11 16:11:14字數 249閱讀 8,139nginx配置http強制跳轉https
很多網站雖然支援 https, 但是直接在瀏覽器位址列輸入網址後, 預設仍是以 http 協議去訪問的, http 強制跳轉 https 的需求應運而生, 以下介紹三種實現的方式
rewrite 方法
這是最常用的實現方法, 將所有 http 請求通過 rewrite 重定向到 https 即可
server {
listen 80;
server_name docs.lvrui.io
rewrite ^(.*)$ https://$host$1 permanent;
# return 302 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name docs.lvrui.io;
index index.html index.htm;
access_log /var/log/nginx/docs.log main;
ssl on;
ssl_certificate /etc/ssl/docs.20150509.cn.crt;
ssl_certificate_key /etc/ssl/docs.20150509.cn.key;
error_page 404 /404.html;
location / {
root /var/www/html/docs;
}
}
497 狀態碼
error code 497: normal request was sent to HTTPS
在一個站點只允許 https 訪問時, 如果使用 http 訪問會報出497錯誤碼
利用497狀態碼重定向到 https
server { listen 80; server_name docs.lvrui.io error_page 497 https://$host$uri?$args; } server { listen 443 ssl; server_name docs.lvrui.io; index index.html index.htm; access_log /var/log/nginx/docs.log main; ssl on; ssl_certificate /etc/ssl/docs.20150509.cn.crt; ssl_certificate_key /etc/ssl/docs.20150509.cn.key; error_page 404 /404.html; location / { root /var/www/html/docs; } }
index.html 重新整理網頁
上面兩種方法均會耗費伺服器資源, 我們使用 curl 來看下百度是如何實現的baidu.com向www.baidu.com的跳轉
$ curl baidu.com -vv * Rebuilt URL to: baidu.com/ * Trying 220.181.57.217... * TCP_NODELAY set * Connected to baidu.com (220.181.57.217) port 80 (#0) > GET / HTTP/1.1 > Host: baidu.com > User-Agent: curl/7.51.0 > Accept: */* > < HTTP/1.1 200 OK < Date: Sat, 01 Apr 2017 06:32:35 GMT < Server: Apache < Last-Modified: Tue, 12 Jan 2010 13:48:00 GMT < ETag: "51-47cf7e6ee8400" < Accept-Ranges: bytes < Content-Length: 81 < Cache-Control: max-age=86400 < Expires: Sun, 02 Apr 2017 06:32:35 GMT < Connection: Keep-Alive < Content-Type: text/html < <html> <meta http-equiv="refresh" content="0;url=http://www.baidu.com/"> </html> * Curl_http_done: called premature == 0 * Connection #0 to host baidu.com left intact
可以看到百度很巧妙的利用meta的重新整理作用,將baidu.com跳轉到www.baidu.com
同理, 我們也可以用這個特性來實現http向https的跳轉
# index.html
<html>
<meta http-equiv="refresh" content="0;url=https://docs.lvrui.io/">
</html>
server {
listen 80;
server_name docs.lvrui.io;
location / {
# 將 index.html 檔案放到下面的目錄下
root /var/www/html/refresh/;
}
}
server {
listen 443 ssl;
server_name docs.lvrui.io;
index index.html index.htm;
access_log /var/log/nginx/docs.log main;
ssl on;
ssl_certificate /etc/ssl/docs.20150509.cn.crt;
ssl_certificate_key /etc/ssl/docs.20150509.cn.key;
error_page 404 /404.html;
location / {
root /var/www/html/docs;
}
}