Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Example Nginx (> 1.9) configuration for adding cross-origin resource sharing (CORS) support to reverse proxied APIs. Handle error status (4xx, 5xx) and expose headers.
# CORS header support
# One way to use this is by placing it into a file called "cors_support.conf"
# under your Nginx configuration directory and placing the following
# statement inside your location block(s):
# include cors_support.conf;
# A limitation to this method is that Nginx doesn't currently send headers
# specified by add_header when the backend returns a 4xx or 5xx status code.
# For more information on CORS, please see:
# Forked from this Gist:
# Check origin, add headers and define $test
if ($http_origin ~* '^https?://(localhost|www\.yourdomain\.com|www\.yourotherdomain\.com)$') {
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,X-Mx-ReqToken,X-Requested-With' always;
# required to be able to read Authorization header in frontend
add_header 'Access-Control-Expose-Headers' 'Authorization' always;
set $test A;
# Update $test variable if this is a preflight request
if ($request_method = 'OPTIONS') {
set $test "${test}B";
# If origin is allowed and is a preflight request, return 204
if ($test = 'AB') {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
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';
return 204;

This comment has been minimized.

Copy link

@Longwater1234 Longwater1234 commented Jun 18, 2021

Please edit line 18. to avoid regex attacks. change to
if ($http_origin ~* '^https?://(localhost|www\.yourdomain\.com|www\.yourotherdomain\.com)$')


This comment has been minimized.

Copy link
Owner Author

@habovh habovh commented Jun 18, 2021

@Longwater1234 thanks for the heads up!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment