Skip to content

Instantly share code, notes, and snippets.

@image72
Forked from agouriou/nginx.conf
Last active July 22, 2016 07:50
Show Gist options
  • Save image72/aa0ebce76ca2b30a521b49442ea7d44d to your computer and use it in GitHub Desktop.
Save image72/aa0ebce76ca2b30a521b49442ea7d44d to your computer and use it in GitHub Desktop.
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. support subdomain
#
# CORS header support
#
# One way to use this is by placing it into a file called "cors_support"
# under your Nginx configuration directory and placing the following
# statement inside your location block(s):
#
# include cors_support;
#
# 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: http://enable-cors.org/
# Forked from this Gist: https://gist.github.com/michiel/1064640
#
set $cors '';
# original condition: $http_origin ~* 'https?://(localhost|www\.yourdomain\.com|www\.yourotherdomain\.com)'
if ($http_origin ~* (https?://(.+\.)?(domain1|domain2|domain3)\.(?:me|co|com)$) {
set $cors 'true';
}
# always is required to add headers even if response's status is 4xx or 5xx
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,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;
}
# 2 if are required, nginx treats each if block as a different context
if ($request_method = 'OPTIONS') {
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment