-
-
Save meglio/47f7dceac14e865e926b to your computer and use it in GitHub Desktop.
Nginx configuration for CORS-enabled HTTPS proxy with origin white-list defined by a simple regex
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
# | |
# Acts as a nginx HTTP proxy server | |
# enabling CORS only to domains matched by regex | |
# | |
server { | |
listen 80; | |
server_name corsproxy.mydomain.com; | |
location / { | |
proxy_redirect off; | |
proxy_set_header Host $arg_proxy_target_domain; | |
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; | |
# Nginx doesn't support nested If statements, so we | |
# concatenate compound conditions on the $cors variable | |
# and process later | |
# If request comes from allowed subdomain then we enable CORS | |
if ($http_origin ~* (https?://example\.com$)) { | |
set $cors "1"; | |
} | |
# OPTIONS indicates a CORS pre-flight request | |
if ($request_method = 'OPTIONS') { | |
set $cors "${cors}o"; | |
} | |
# Append CORS headers to any request from | |
# allowed CORS domain, except OPTIONS | |
if ($cors = "1") { | |
add_header 'Access-Control-Allow-Origin: $http_origin' always; | |
add_header 'Access-Control-Allow-Credentials: true' always; | |
proxy_pass $arg_proxy_target_protocol://$arg_proxy_target_domain; | |
} | |
# OPTIONS (pre-flight) request from allowed | |
# CORS domain. return response directly | |
if ($cors = "1o") { | |
add_header 'Access-Control-Allow-Origin: $http_origin' always; | |
add_header 'Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE' always; | |
add_header 'Access-Control-Allow-Credentials: true' always; | |
add_header 'Access-Control-Allow-Headers: Origin,Content-Type,Accept' always; | |
add_header Content-Length 0; | |
add_header Content-Type text/plain; | |
return 204; | |
} | |
# Requests from non-allowed CORS domains | |
proxy_pass $arg_proxy_target_protocol://$arg_proxy_target_domain; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example request:
Will request the following URL: