Skip to content

Instantly share code, notes, and snippets.

@meglio
Forked from pauloricardomg/cors.nginxconf
Last active March 18, 2016 05:46
Show Gist options
  • Save meglio/47f7dceac14e865e926b to your computer and use it in GitHub Desktop.
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
#
# 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;
}
}
@meglio
Copy link
Author

meglio commented Mar 18, 2016

Example request:

http://corsproxy.mydomain.com/latest.json?proxy_target_protocol=https&arg_proxy_target_domain=meta.discourse.org&order=activity

Will request the following URL:

https://meta.discourse.org/latest.json?proxy_target_protocol=http&arg_proxy_target_domain=meta.discourse.org&order=activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment