nginx CORS whitelist map

Above your server {} block, you need to add a whitelist map.

map $http_origin $cors_header{
  default "";
  include /etc/nginx/cors-whitelist.map;
}

Then you need to create a cors-whitelist.map file in /etc/nginx.

"~^(http:\/\/localdomain1\.com)$" "$http_origin";
"~^(http:\/\/localdomain3\.com)$" "$http_origin";

And finally, add in the appropriate headers in your server block:

server {
  listen 80;
  listen [::]:80;

  add_header 'Access-Control-Allow-Origin' "$cors_header";
  add_header 'Access-Control-Allow-Credentials' 'true';
  add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';

root /var/www/html;
[...]

It’s a little redundant in the map file, but it maximizes readability if you have a lot of servers that need CORS access.

Advertisements
nginx CORS whitelist map

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s