如何通过nginx解决跨域问题
nginx版本 1.29.1
问题
10.20.4.1 访问这个10.20.4.2:5000服务跨域了,麻烦处理一下
跨域报错
![]()
根据您图片中的错误信息,前端运行在 http://10.20.4.1,试图向 http://10.20.4.2:50000/upload发送 POST 请求,但被 CORS 策略阻止,因为响应中没有 Access-Control-Allow-Origin头部。
应该5000是python端口
我采用了nginx代理,添加允许跨域
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
# 动态设置允许的CORS源
# 1. 检查 map 块:确保包含 http://10.20.4.1
map $http_origin $cors_allowed_origin {
default "";
"http://10.20.4.1" "http://10.20.4.1"; # 必须存在这一行
"http://10.20.4.2" "http://10.20.4.2"; # 必须存在这一行
# ... 其他允许的来源
}
server {
listen 50000;
server_name 10.20.4.2;
# 2. 检查 server 或 location 块:确保添加了 CORS 头
location / {
# 处理 OPTIONS 预检请求
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' $cors_allowed_origin;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' '*';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Length' 0;
add_header 'Content-Type' 'text/plain; charset=utf-8';
return 204;
}
# 反向代理到后端
proxy_pass http://10.20.4.2:5000;
# ... 其他 proxy_set_header ...
# 为实际响应添加 CORS 头,使用 always 确保任何状态码都添加
add_header 'Access-Control-Allow-Origin' $cors_allowed_origin always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' '*' always;
}
}
}测试实际 POST 请求
此命令模拟前端实际发送的 POST 请求,检查响应是否包含 CORS 头部。
curl -X OPTIONS "http://10.20.4.2:50000" \ -H "Origin: http://10.20.4.1" \ -H "Access-Control-Request-Method: POST" \ -H "Access-Control-Request-Headers: content-type" \ -v

到此这篇关于通过nginx解决跨域问题的文章就介绍到这了,更多相关nginx解决跨域内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Nginx0.5.33+PHP5.2.5(FastCGI)搭建胜过Apache10倍的Web服务器
Nginx 0.5.31 + PHP 5.2.4(FastCGI)搭建可承受3万以上并发连接数,胜过Apache 10倍的Web服务器的第2版,经过了多台服务器的测试。2009-10-10
nginx 多个location转发任意请求或访问静态资源文件的实现
这篇文章主要介绍了nginx 多个location转发任意请求或访问静态资源文件的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-11-11
nginx搭建图片服务器的过程详解(root和alias的区别)
这篇文章主要介绍了nginx搭建图片服务器(root和alias的区别)的过程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2020-10-10
nginx ingress代理websocket流量的配置方法
ingress nginx默认支持websocket协议,使用长连接协议时需要注意连接超时的设置,文中有提到读取和发送超时的注解参数,通过本文阅读可以快速掌握,对nginx ingress代理websocket相关知识感兴趣的朋友一起看看吧2022-03-03


最新评论