Cross-Origin Resource Sharing (CORS) is a web security feature that controls how web pages can request resources from a different domain than the one that served the web page. Without CORS restrictions, any website could make requests to other sites where a user is logged in.
This blog explains how to configure CORS when using Nginx as a reverse proxy. By handling CORS at the Nginx layer, we can centralize and simplify cross-origin access control for multiple backend applications.
Pre-requisites: Nginx Configured as reverse proxy
In this sample, we have multiple sites with site-specific allowed origins. To enable CORS in Nginx for the given scenario, we need to add similar configuration as shown below.
map "$host:$http_origin" $cors_origin {
"site01-core.exmaple.cloud:https://cors-test.codehappy.dev" $http_origin;
"site02-core.example.cloud:https://another-origin.dev" $http_origin;
"site03-core.example.cloud:https://something-else.dev" $http_origin;
default "";
}- $host:$http_origin is the key. it combines the request’s hostname and origin to identify each site’s CORS rule.
- $http_origin represent the allowed origin for that specific site.
- $cors_origin is the new variable. it stores the result of the mapping. It will be used later in the Nginx configuration to set the CORS headers.
- If no match is found, $cors_origin is set to the default value ("")
After the mapping, add the below configuration under the location / block in nginx.conf file.
if ($request_method = OPTIONS) {
add_header 'Access-Control-Allow-Origin' "$cors_origin" always;
add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Encoding,Content-Type,Accept-Encoding,Cache-Control,If-Modified-Since,If-Unmodified-Since,If-Match,If-None-Match,X-Requested-With,User-Agent' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, PATCH, PUBLISH, REVOKE, DELETE' always;
add_header 'Access-Control-Expose-Headers' 'Content-Encoding,Cache-Control,Vary,Last-Modified,ETag,Location,X-RequestId' always;
return 204;
}
add_header 'Access-Control-Allow-Origin' "$cors_origin" always;
add_header 'Access-Control-Expose-Headers' 'Content-Encoding,Cache-Control,Vary,Last-Modified,ETag,Location,X-RequestId' always;
When a browser makes a cross-origin request, it first sends preflight request to check the permissions and verify whether the target server allows the request, If the server responds with valid CORS headers, then send the actual request.
No comments:
Post a Comment