Last active
February 12, 2020 18:21
-
-
Save vjrj/529a85ed09de7f857e462be299434401 to your computer and use it in GitHub Desktop.
nginx include config to enable cors to domains and subdomains in LA sites
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
# Use with | |
# include /etc/nginx/conf.d/cors; | |
# in your locations | |
# Allow static fonts | |
location ~* .(eot|otf|svg|ttf|woff|woff2)$ { | |
add_header Access-Control-Allow-Origin *; | |
} | |
set $cors ''; | |
# Edit this regexp with your sub/domains | |
# Test your regexp of type PCRE with a tool like https://www.regextester.com/ | |
if ($http_origin ~* '^https?:\/\/(localhost|l-a\.site|.*\.l-a\.site)') { | |
set $cors 'C'; | |
} | |
# As multiple ifs are not allowed we follow this option | |
# http://rosslawley.co.uk/archive/old/2010/01/04/nginx-how-to-multiple-if-statements/ | |
if ($request_method = GET) { | |
set $cors '${cors}GET'; | |
} | |
if ($request_method = POST) { | |
set $cors '${cors}POST'; | |
} | |
if ($request_method = OPTIONS) { | |
set $cors '${cors}OPTIONS'; | |
} | |
# This is modified version of: https://enable-cors.org/server_nginx.html restricting to previous regexp | |
if ($cors = COPTIONS) { | |
add_header 'Access-Control-Allow-Origin' '*'; | |
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; | |
# | |
# Custom headers and headers various browsers *should* be OK with but aren't | |
# | |
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'; | |
# | |
# Tell client that this pre-flight info is valid for 20 days | |
# | |
add_header 'Access-Control-Max-Age' 1728000; | |
add_header 'Content-Type' 'text/plain; charset=utf-8'; | |
add_header 'Content-Length' 0; | |
return 204; | |
} | |
if ($cors = CPOST) { | |
add_header 'Access-Control-Allow-Origin' '*'; | |
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; | |
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'; | |
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range'; | |
} | |
if ($cors = CGET) { | |
add_header 'Access-Control-Allow-Origin' '*' always; | |
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; | |
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'; | |
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment