网站制作学习网经验与学习→正文:nginx指定多域名跨域
字体:

nginx指定多域名跨域

经验与学习 2024/10/26 14:45:33  点击:不统计

%77w%77%2Ef%6F%72p%73%70%2Ec%6E

 nginx 配置多域名或者单域名允许跨域访问接口,实际中https只能访问https 的http访问http的不能交叉访问
 
1. 单个域名跨域:
   server {
listen xxx:
server_name forasp.cn
location / {
add_header 'Access-Control-Allow-Origin' 'http://192.168.5.191:9527'; #某个IP 或者域名+端口,
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, Authorization,Userid,Timestamp,X-Request-ID'; #这里自定义请求header 参数

if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' 'http://192.168.5.191:9527'; #某个IP 或者域名+端口,
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, Authorization,Userid,Timestamp,X-Request-ID'; #这里自定义请求header 参数 同上
add_header 'Access-Control-Max-Age' 3600;
return 204; # No content
}
}
}
   
2. 多个域名跨域
   # 采用map 定义全局的 http_origin 和cross_origin
map $http_origin $cors_origin {
default "";
http://192.168.5.191:9527 "http://192.168.5.191:9527";
http://test.deepbi.com "http://test.deepbi.com";
}

server {
listen xxx:
server_name forasp.cn
location / {
add_header 'Access-Control-Allow-Origin' $cors_origin; # 采用map 形式定义多个
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, Authorization,Userid,Timestamp,X-Request-ID';

if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' $cors_origin; # 采用map 形式定义多个
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, Authorization,Userid,Timestamp,X-Request-ID';
add_header 'Access-Control-Max-Age' 3600;
return 204; # No content
}
}
}
   
3. 任意域名跨域 ,注意在任意* 域名配置情况下,如果需要cookie支持凭证是不支持的。即 无状态,只有数据
   server {
listen 80;
server_name forasp.cn;

location / {
# 允许所有来源
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true'; # 如果需要支持凭证,需将此行去掉
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept';

# 处理 OPTIONS 请求
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true'; # 如果需要支持凭证,需将此行去掉
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, Authorization,Userid,Timestamp,X-Request-ID';
add_header 'Access-Control-Max-Age' 3600;
add_header 'Content-Length' 0;
return 204;
}
}
}
   
 
以上就是nginx 跨域配置
 

http://www.forasp.cn/

·上一篇:git提交代码到2个托管地址 >>    ·下一篇:nginx 配置conf直接返回测试nginx可用 >>
推荐文章
最新文章