Skip to content

Instantly share code, notes, and snippets.

@mbijon
Forked from Stanback/nginx.conf
Last active January 26, 2022 15:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbijon/572e8acf1f6a789d7d529ed2b2c8f17e to your computer and use it in GitHub Desktop.
Save mbijon/572e8acf1f6a789d7d529ed2b2c8f17e to your computer and use it in GitHub Desktop.
Nginx CORS-support for proxied Grape/Rails/Passenger APIs
#
# CORS-header support example while nginx proxies Rails/Grape + Passenger
# ...not a complete config file
#
server {
listen 443 ssl;
root /foo/public;
# Modify for API-specific
try_files $uri/index.html $uri @passenger;
location @passenger {
passenger_enabled on;
# Set must be inside the location{...} block
set $cors '';
# Terminate regex with `\Z` to prevent forged `Origin: http://badregex.main.com.evil.com` from being allowed
if ($http_origin ~ '^https?://((?:\w)+\.main\.com|(?:\w)+\.secondary\.com)\Z') {
set $cors 'true';
}
# Forcing a strict CORS policy in case domain doesn't match regex
if ($cors = '') {
set $http_origin 'https://www.main.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,X-Requested-With' always;
}
if ($request_method = 'OPTIONS') {
# NOTE: Chrome max is 10mins, Firefox max 24hrs
# ...setting a reasonable 1hr, though Chrome will just use 10mins
add_header 'Access-Control-Max-Age' 3600;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment