nginx 如何强制跳转 https

本项目 nginx 作为代理服务

项目上线,客户说要加个安全证书 ,于是安全证书是加上了,可是htttp和https都能访问网站,客户要求不行必须强制用带有https的地址访问

开整

这是 http 和https 都能访问的 nginx.conf  关键配置

    server {

        listen       80;
        listen       443 ssl;
        
        server_name  xxxxon.com www.xxx.com;
        
        
        ssl_certificate      /usr/local/server/cert/xxx.com_bundle.pem;
        ssl_certificate_key  /usr/local/server/cert/xxx.com.key;

        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;

        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;

        location / {
            proxy_pass http://1x6.1x.1xx.138:8888;
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

    }

因为监听了两个端口号 导致http和https都能访问   注:443是监听ssl证书的端口 80是默认端口

改成以下这样即可

    server {

        listen       80;
        
        server_name  xxxx.com www.xxxx.com;
        
        return 301 https://$server_name$request_uri;
    }
    
    server {

        listen       443 ssl;
        
        server_name  xxxx.com www.xxxx.com;
        
        
        ssl_certificate      /usr/local/server/cert/xxxx.com_bundle.pem;
        ssl_certificate_key  /usr/local/server/cert/xxxx.com.key;

        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;

        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;

        location / {
            proxy_pass http://xxx.xx.xxx.xxx:8888;
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

    }

第一个服务端口是监听80,重定向到带有https 的协议的端口 也就是下面那一个443端口 

第二个本来就是 ssl端口 不用管控

 

已解决

 

还有一种方式告诉大家,也是无意间知道的 ,用mate页面刷新的方式

创建个html页面 ,插入这一句

<html>
<meta http-equiv="refresh" content="0;url=https://baidu.com/">
</html>

当你打开这个页面的时候 ,自然会重定向到带有安全证书的百度页面

这种方式你们可以自由发挥

 

posted @ 2022-02-12 14:04  lanwf  阅读(2174)  评论(0编辑  收藏  举报