nginx跨域访问设置

1、ngxin跨域访问错误提示

Access to fetch at 'http://ip:端口/' from origin 'http://域名' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

2、nginx添加配置

 add_header 'Access-Control-Allow-Origin' $http_origin;
 add_header 'Access-Control-Allow-Credentials' 'true';
 add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
 add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
 add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
 if ($request_method = 'OPTIONS') {
 add_header 'Access-Control-Max-Age' 1728000;
 add_header 'Content-Type' 'text/plain; charset=utf-8';
 add_header 'Content-Length' 0;
 return 204;
}

3、查看配置文件是否正确

ps -ef|grep nginx 根据结果查看启动项,在启动项路径下进行验证:
./nginx -t
./nginx -s reload
Docker是一个开源的容器化平台,可以帮助我们在不同的操作系统上快速构建、打包和运行应用程序。而Nginx是一种常用的高性能Web服务器,也被广泛用作反向代理服务器。在使用Docker部署Nginx时,有时可能会遇到访问的问题。 访问是指在浏览器中,页面使用的是一个名,而请求的接口却是另一个名的情况。由于浏览器的同源策略限制,请求会被阻止。为了解决这个问题,我们可以通过在Nginx配置中添加设置来实现访问。 下面是一个简单的示例: 1. 首先,在Docker中安装Nginx,并创建一个新的Nginx容器。 ``` docker run -d -p 80:80 --name mynginx nginx ``` 2. 在Nginx容器的配置文件中添加设置。 ``` docker exec -it mynginx /bin/bash vi /etc/nginx/conf.d/default.conf ``` 在配置文件中添加以下内容: ``` location / { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS'; add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'; add_header Access-Control-Allow-Credentials 'true'; if ($request_method = 'OPTIONS') { add_header Access-Control-Max-Age 1728000; add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS'; add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'; add_header Content-Type 'text/plain; charset=utf-8'; add_header Content-Length 0; return 204; } } ``` 保存并退出配置文件,然后重新启动Nginx容器。 ``` exit docker restart mynginx ``` 现在,您的Nginx容器应该已经配置为允许访问。 请注意,上述配置中使用了通配符*,这意味着允许任何名进行访问。在生产环境中,为了提高安全性,建议将通配符替换为实际允许的名。 总结:通过在Nginx配置文件中添加设置,我们可以实现Docker中Nginx访问。这种方法可以确保您的Web应用程序能够正常运行并接受来自其他名的请求。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值