zoukankan      html  css  js  c++  java
  • nginx配置http强制跳转https

    nginx配置http强制跳转https

    网站添加了https证书后,当http方式访问网站时就会报404错误,所以需要做http到https的强制跳转设置.

    一、采用nginx的rewrite方法

    1.下面是将所有的http请求通过rewrite重写到https上。

    例如将web.heyonggs.com域名的http访问强制跳转到https。

    server
    {
    listen 80;
    server_name web.heyonggs.com;
    rewrite ^(.*)$ https://$host$1 permanent;    //这是nginx早前的写法,现在还可以使用
    }

    上面的跳转配置rewrite ^(.*)$  https://$host$1 permanent;

    也可以改为下面

    server
    {
    listen 80;
    server_name web.heyonggs.com;
    rewrite ^/(.*)$ http://web.heyonggs.com/$1 permanent;
    }

    或者

    server
    {
    listen 80;
    server_name web.heyonggs.com;
    rewrite ^ http://web.heyonggs.com$request_uri? permanent;
    }

     

    2.最新的写法

    server
    {
    listen 80;
    server_name web.heyonggs.com;
    return 301 https://$server_name$request_uri;  //最新写法
    }

     

    3.这种方式适用于多域名的时候,即访问heyonggs.com的http也会强制跳转到https://web.heyonggs.com上面

    server
    {
    listen 80;
    server_name heyonggs.com web.heyonggs.com;
    if ($host ~* "^heyonggs.com$") {
    rewrite ^/(.*)$ https://web.heyonggs.com/ permanent;
    }
    }

     4.下面是最简单的一种配置

    server
    {
    listen 80;
    server_name web.heyonggs.com;
    if ($host = "web.heyonggs.com") {
    rewrite ^/(.*)$ http://web.heyonggs.com permanent;
    }
    }

     二、采用nginx的497状态码

    497 - normal request was sent to HTTPS

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

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

    配置实例:如下访问web.heyonggs.com或者heyonggs.com的http都会被强制跳转到https

    server
    {
    listen 80;
    server_name web.heyonggs.com;
    error_page 497  https://$host$uri?$args;
    }

    也可以将80和443的配置放在一起:

    server
    {
    listen 80;
    listen 443;
    server_name web.heyonggs.com;
    error_page 497  https://$host$uri?$args;
    }

    三、利用meta的刷新作用将http跳转到https

    上述的方法均会耗费服务器的资源,可以借鉴百度使用的方法:巧妙的利用meta的刷新作用,将http跳转到https

    可以基于http://dev.wangshibo.com的虚拟主机路径下写一个index.html,内容就是http向https的跳转
     
    将下面的内容追加到index.html首页文件内
    [root@localhost ~]# cat /var/www/html/8080/index.html
    <html> 
    <meta http-equiv="refresh" content="0;url=https://web.heyonggs.com/"> 
    </html>

    nginx的配置文件

    server
    {
    listen 80;
    listen 443;
    server_name web.heyonggs.com;

    #将404的页面重定向到https的首页 error_page
    497 https://$host$uri?$args; }

    四、通过proxy_redirec方式

    解决办法:
    # re-write redirects to http as to https, example: /home
    proxy_redirect http:// https://;
  • 相关阅读:
    LOJ#3212. 「CSP-S 2019」划分
    矩阵乘法
    SSF信息社团4月训练题目整理
    AtCoder Regular Contest 116
    SSF信息社团3月训练题目整理
    Codeforces Round #704 (Div. 2)
    SSF信息社团寒假训练题目整理(三)
    关于 zzt 得 0.8 分这件事
    Luogu P7244 章节划分
    SSF信息社团寒假训练题目整理(二)
  • 原文地址:https://www.cnblogs.com/heyongboke/p/10282336.html
Copyright © 2011-2022 走看看