使用http访问页面时,将其跳转成https

由于项目业务升级,网站升级 https 协议。
HTTPS 承载的页面上不允许出现 http 请求,一旦出现就是提示或报错:

Mixed Content: The page at 'https://www.example.com' was loaded over HTTPS, 
but requested an insecure image ‘http://static.example.com/test.jpg’. 
This content should also be served over HTTPS.

因此即使使用到的域名对http请求已经强制了 https ,但是在页面中浏览器对于http请求压根就不会发送,那么就必需替换页面上所有的 http为https ,而我遇到的是个使用了十年的老系统,代码中有很多硬编码的 http 地址,一一替换的话要替换2万多行…

于是从 http协议 入手,在响应 header 中添加 upgrade-insecure-requests ,即在 php入口 文件中添加:

header("Content-Security-Policy: upgrade-insecure-requests");

或着也可以在由前端在 html 页面中添加 meta

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" />

或者在 nginx 配置中进行 header 的添加:

server {
  listen       443;
  server_name  www.example.com;
  error_log  /logs/nginx/error.log;
  root /var/www/www.example.com;
  index  index.php index.html index.htm;
  ssl on;
  ssl_certificate   cert/test/test.pem;
  ssl_certificate_key  cert/test/test.key;
  ssl_session_timeout 5m;

  #添加响应头
  add_header Content-Security-Policy "upgrade-insecure-requests'";
  
  location / {
     if (!-f $request_filename){
       rewrite ^/(.*)$ /index.php?s=$1 last;
       break;
     }
     limit_except GET POST DELETE PUT {
       deny all;
     }
  }
}
从而让浏览器对页面中的所有http请求,都升级为https协议发送请求,从而省去了逐一修改url的协议的麻烦。

以上,希望对大家有帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值