在nginx中使用反向代理在子域上允许cors [英] allow cors on subdomain with reverse proxy in nginx
本文介绍了在nginx中使用反向代理在子域上允许cors的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
根据MS文档,我需要为我的Web API设置反向代理.以下是带有cors&的nginx配置反向代理设置:
As per the MS doc, I need to set up a reverse proxy for my web api. The below is the nginx config with cors & reverse proxy settings:
server {
listen 80;
listen [::]:80;
server_name api.ZZZ.com;
set $cors '';
location / {
if ($http_origin ~ '^https?://(localhost|www\.ZZZ\.com|www\.ZZZ\.com|ZZZ\.com)') {
set $cors 'true';
}
if ($cors = 'true') {
add_header 'Access-Control-Allow-Origin' "$http_origin" always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,Width,X-Requested-With' always;
# required to be able to read Authorization header in frontend
add_header 'Access-Control-Expose-Headers' 'Authorization' always;
}
if ($request_method = 'OPTIONS') {
# Tell client that this pre-flight info is valid for 20 days
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
proxy_pass http://localhost:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
我的startup.cs
中也包含以下内容:
I also have the following in my startup.cs
:
services.AddCors(options =>
{
options.AddPolicy(corsName, builder =>
{
builder.WithOrigins("http://www.ZZZ.com", "http://ZZZ.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
及更高版本:
app.userCors(corsName);
但是我仍然收到以下CORS错误:
But I am still getting the below CORS error:
Access to XMLHttpRequest at 'http://api.ZZZ.com/YYY' from origin 'http://www.ZZZ.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
请帮助!
推荐答案
您可以尝试使用SetIsOriginAllowedToAllowWildcardSubdomains
配置并添加通配符子域吗?像这样.
Can you try with SetIsOriginAllowedToAllowWildcardSubdomains
configuration and adding wildcard subdomain? like this.
在ConfigureServices
方法中.
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder
.SetIsOriginAllowedToAllowWildcardSubdomains()
.WithOrigins("https://*.example.com","https://example.com")
.AllowAnyMethod()
.AllowCredentials()
.AllowAnyHeader()
.Build()
);
});
在Configure
方法中
app.UseCors("CorsPolicy");
这篇关于在nginx中使用反向代理在子域上允许cors的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文