-
-
Save mbijon/572e8acf1f6a789d7d529ed2b2c8f17e to your computer and use it in GitHub Desktop.
Nginx CORS-support for proxied Grape/Rails/Passenger APIs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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