阅读

nginx跨域配置

Nginx  2024-02-01 09:58

1、配置文件 server 内增加

# 允许跨域请求的域名,* 表示允许所有域名访问
add_header Access-Control-Allow-Origin '*';
# 允许跨域请求的方法
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
# 允许跨域请求的自定义 Header
add_header Access-Control-Allow-Headers 'Accept, Authorization, Cache-Control, Content-Type, DNT, If-Modified-Since, Keep-Alive, Origin, User-Agent, X-Mx-ReqToken, X-Requested-With';
# 允许跨域请求的 Credential
add_header Access-Control-Allow-Credentials 'true';
# 预检请求的存活时间,即 Options 请求的响应缓存时间
add_header Access-Control-Max-Age 3600;

# 处理预检请求
if ($request_method = 'OPTIONS') {
    return 204;
}

2、多域名配置参考

# 修改 Access-Control-Allow-Origin
set $cors_origin "";
if ($http_origin ~* "^https://www.aaa.com$") {
  set $cors_origin $http_origin;
}
if ($http_origin ~* "^https://www.bbb.com$") {
  set $cors_origin $http_origin;
}
add_header Access-Control-Allow-Origin $cors_origin;


广告

【腾讯云】618云上GO!云服务器限时秒杀,1核2G首年95元!
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。

广告

618优惠礼包限时领取,更有2000元飞天会员礼包等你来拿
上云优惠聚集地,云小站专属代金券可叠加产品折扣使用