Loading... ## 基于 nginx 搭建了一个 https 访问的虚拟主机,监听的域名是 test.com,但是很多用户不清楚 https 和 http 的区别,会很容易敲成 http://test.com,这时会报出404错误,所以我需要做基于 test.com 域名的 http 向 https 的强制跳转 ## 1. nginx 的 rewrite 方法 这应该是大家最容易想到的方法,将所有的http请求通过rewrite重写到https上即可 配置: ``` server { listen 192.168.1.111:80; server_name test.com; rewrite ^(.*)$ https://$host$1 permanent; } ``` 搭建此虚拟主机完成后,就可以将http://test.com的请求全部重写到https://test.com上了 ## 2. nginx 的 497 状态码 error code 497 ``` 497 - normal request was sent to HTTPS ``` 利用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 497 https://$host$uri?$args; } ``` ## 3. index.html 刷新网页 百度很巧妙的利用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_name test.com; location / { #index.html放在虚拟主机监听的根目录下 root /srv/www/http.test.com/; } #将404的页面重定向到https的首页 error_page 404 https://test.com/; } ``` 最后修改:2020 年 08 月 28 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 哇卡哇卡