沙滩星空的博客沙滩星空的博客

nginx强制https访问(http强制跳转https)

nginx的rewrite方法
将所有的http请求通过rewrite重写到https上

server
    {
        listen 80;
        server_name pay.12121.com pay1.12121.com;
        rewrite ^(.*)$ https://${server_name}$1 permanent;
    }

nginx的497状态码
当此虚拟站点只允许https访问时,当用http访问时nginx会报出497错误码
利用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;  
}

index.html刷新网页

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

可以看到百度巧妙的利用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/;  
}

nginx强制使用https访问(http跳转到https) https://www.cnblogs.com/yun007/p/3739182.html

未经允许不得转载:沙滩星空的博客 » nginx强制https访问(http强制跳转https)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址