Skip to content

Instantly share code, notes, and snippets.

@luison
Last active December 10, 2020 19:27
Show Gist options
  • Save luison/4afc6caa962d5c9168a740b42c7d20b7 to your computer and use it in GitHub Desktop.
Save luison/4afc6caa962d5c9168a740b42c7d20b7 to your computer and use it in GitHub Desktop.
Optimized NGINX CORS with more_header
# our server config for CORS as optimized as we can, supporting multiple domains, add_more_header and trying to avoid ifs as much as possible
# by Jose Luis Moya (alsur.es)
# sources include:
# https://gist.github.com/alexjs/4165271
# @todo need to confirm if more_set_headers 'Access-Control-Allow-Origin: $http_origin'; being http_origin blank would unset or blank
# in this case we would rather use https://enable-cors.org/server_nginx.html method
# map aceptable domains, var will be assigned if it coincides only
# map $http_origin $allow_origin {
# ~^https?://(.*\.)?my-domain.com(:\d+)?$ $http_origin;
# # add other domains here
# # NGINX won't set empty string headers, so if no match, header is unset.
# default "";
# }
### CORS
# Nginx doesn't support nested If statements, so we
# concatenate compound conditions on the $cors variable
# and process later
# server should be somewhere here
# Only if request comes from allowed subdomain then we enable CORS
if ( $http_origin ~* (https?://(.+\.)?(domain1|domain2|domain3)\.(?:me|co|com)$) ) {
set $cors "1";
}
# locations and server you want this applicable
# we include from here via external common file so it can be reused on other server
# OPTIONS indicates a CORS pre-flight request
if ($request_method = 'OPTIONS') {
set $cors "${cors}options";
}
# Append CORS headers to any request from
# allowed CORS domain, except OPTIONS
if ($cors = "1") {
more_set_headers 'Access-Control-Allow-Origin: $http_origin';
more_set_headers 'Access-Control-Allow-Credentials: true';
more_set_headers 'Access-Control-Allow-Headers: DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
# OPTIONS (pre-flight) request from allowed
# CORS domain. return response directly
if ($cors = "1options") {
more_set_headers 'Access-Control-Allow-Origin: $http_origin';
more_set_headers 'Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE';
more_set_headers 'Access-Control-Allow-Credentials: true';
more_set_headers 'Access-Control-Allow-Headers: Origin,Content-Type,Accept';
more_set_headers 'Content-Length: 0';
more_set_headers 'Content-Type: text/plain';
return 204;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment