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;
}
}
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();
});
});
and later:
app.userCors(corsName);
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.
Please help!
Can you try with SetIsOriginAllowedToAllowWildcardSubdomains
configuration and adding wildcard subdomain? like this.
In the ConfigureServices
method.
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder
.SetIsOriginAllowedToAllowWildcardSubdomains()
.WithOrigins("https://*.example.com","https://example.com")
.AllowAnyMethod()
.AllowCredentials()
.AllowAnyHeader()
.Build()
);
});
And in the Configure
method
app.UseCors("CorsPolicy");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.