配置nginx后,http可以访问,https却无法访问

在部署前后端分离的Vue3+Flask项目时,配置nginx后发现http能正常访问,但https出现错误。错误提示为 Mixed Content,尝试通过设置meta标签和nginx的Content-Security-Policy未解决问题。最终发现,问题在于前端请求URL缺少斜杠,添加斜杠后解决了https访问问题。

一、背景:

前后端分离,前端:vue3,后端:flask

前端打包合并到后端后,需要将该项目部署到正式服务器,并为其配置域名。配置完成后,却出现了http能访问,https无法访问的问题,报错如下:

Mixed Content: The page at 'https://...' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://...'. This request has been blocked; the content must be served over HTTPS.

二、尝试

碰到这个问题的人不少,但是解决方法都类似,都是通过某种方法将http请求强制转成https请求。

第一种:

在页面中加入如下<meta>标签

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

第二种:

nginx配置如下语句

add_header Content-Security-Policy "upgrade-insecure-requests;connect-src *"

这两种方法我都尝试过了,它们的结果是一致的,但是并不理想,没有解决我的问题。通过这两种方法,我得到的结果是https可以访问了,但是http访问时又出现了另外的问题。

三、解决方案

最后,我终于找到了问题的真正所在。是因为前端请求后缺少斜杠。即将下面的请求url

 url: '/api/get_data

改为如下url

 url: '/api/get_data/

 是的,就是这么愚蠢,就是这么简单。

参考:https://www.it1352.com/202186.html

I just spent a good 4 hours trying to fix a similar problem. Here's what solved mine:

Summary: add a trailing '/' to your request

I found this post useful in fixing my problem. Basically, the server doesn't care if you send your request with a trailing '/' or not, because it internally routes to '/' if you don't add it. However, if the routing is happening internally (e.g. nginx passing the request to a local process), you get an http redirect which will make your request fail.

四、 结束语

记录学习之旅,与君共勉

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值