首页 > 运维 > nginx > nginx强制使用https访问的方法有哪些

nginx强制使用https访问的方法有哪些

PHPz
发布: 2023-05-15 23:40:11
转载
2603 人浏览过

nginx的rewrite方法

思路

这应该是大家最容易想到的方法,将所有的http请求通过rewrite重写到https上即可

配置

1

2

3

4

5

6

server {

 listen 111:80;

 server_name testcom;

   

 rewrite ^(*)$ https://$host$1 permanent;

}

登录后复制

搭建此虚拟主机完成后,就可以将http://test.com的请求全部重写到https://test.com上了

nginx的497状态码

error code 497

1

497 - normal request was sent to https

登录后复制

解释:当此虚拟站点只允许https访问时,当用http访问时nginx会报出497错误码

思路

利用error_page命令将497状态码的链接重定向到https://test.com这个域名上

配置

1

2

3

4

5

6

7

8

9

10

11

12

13

14

server {

 listen  11:443; #ssl端口

 listen  11:80; #用户习惯用http访问,加上80,后面通过497状态码让它自动跳到443端口

 server_name testcom;

 #为一个server{}开启ssl支持

 ssl     on;

 #指定pem格式的证书文件

 ssl_certificate  /etc/nginx/testpem;

 #指定pem格式的私钥文件

 ssl_certificate_key /etc/nginx/testkey;

   

 #让http请求重定向到https请求

 error_page 497 https://$host$uri?$args;

}

登录后复制

index.html刷新网页

思路

上述两种方法均会耗费服务器的资源,我们用curl访问baidu.com试一下,看百度的公司是如何实现baidu.com向www.baidu.com的跳转

nginx强制使用https访问的方法有哪些

可以看到百度很巧妙的利用meta的刷新作用,将baidu.com跳转到www.baidu.com.因此我们可以基于http://test.com的虚拟主机路径下也写一个index.html,内容就是http向https的跳转

index.html

1

2

3

<html>

<meta http-equiv="refresh" content="0;url=https://testcom/">

</html>

登录后复制

nginx虚拟主机配置

1

2

3

4

5

6

7

8

9

10

11

server {

 listen 11:80;

 server_name testcom;

   

 location / {

    #indexhtml放在虚拟主机监听的根目录下

  root /srv/www/httptestcom/;

 }

  #将404的页面重定向到https的首页

 error_page 404 https://testcom/;

}

登录后复制

以上是nginx强制使用https访问的方法有哪些的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板