Skip to content

Instantly share code, notes, and snippets.

@developerdino
Created June 22, 2020 05:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save developerdino/74651b046e6799c77068626e7b3fb5de to your computer and use it in GitHub Desktop.
Save developerdino/74651b046e6799c77068626e7b3fb5de to your computer and use it in GitHub Desktop.
CORS nginx config using maps
add_header "Access-Control-Allow-Credentials" $cors_allowed_credentials;
add_header "Access-Control-Allow-Headers" $cors_allowed_headers;
add_header "Access-Control-Allow-Methods" $cors_allowed_methods;
add_header "Access-Control-Allow-Origin" $cors_allowed_origin;
add_header "Access-Control-Max-Age" $cors_max_age;
map $http_origin $cors_is_allowed_origin {
hostnames;
default "false";
"~example(qa|staging)??\.com\.au$" "true";
}
map $request_method $cors_is_allowed_methods {
default "false";
OPTIONS "true";
GET "true";
POST "true";
DELETE "true";
PUT "true";
}
map "$cors_is_allowed_origin:$cors_is_allowed_methods" $cors_is_allowed {
default "false";
"true:true" "true";
}
# this is a proxy for the credentials cors header
map $cors_is_allowed $cors_allowed_credentials {
default "";
"true" "true";
}
map $cors_is_allowed $cors_allowed_headers {
default "";
"true" "origin, x-requested-with, content-type, accept, pragma";
}
map $cors_is_allowed $cors_allowed_methods {
default "";
"true" "DELETE, GET, POST, OPTIONS, PUT";
}
map "$request_method:$cors_is_allowed" $cors_max_age {
default "";
"OPTIONS:true" "1728000";
}
map $cors_is_allowed $cors_allowed_origin {
default "";
"true" $http_origin;
}
http {
# all your standard http config here
# ...
include /etc/nginx/conf.d/maps.conf;
server {
listen [::]:80 default_server;
listen 80 default_server;
server_name _;
charset utf-8;
autoindex off;
sendfile off;
rewrite_log on;
log_not_found on;
root /var/www/html;
index index.html;
include /etc/nginx/conf.d/headers.conf;
# Handle preflight requests
if ($request_method = "OPTIONS") {
return 204;
}
# locations go here
# ...
}
}
@developerdino
Copy link
Author

This is a config I came up with for NGINX using maps instead of ifs based on If is Evil. Would love some feedback on whether this is a valid approach or there is a better way to do this?

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