Skip to content

Instantly share code, notes, and snippets.



Forked from Stanback/nginx.conf
Last active Oct 19, 2019
What would you like to do?
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:` 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 ' ';
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