nginx CORS whitelist map

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

map $http_origin $cors_header{
  default "";
  include /etc/nginx/;

Then you need to create a 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.


Published by EyeOfMidas

Game Programmer, Web Developer, Linux Server Admin

Leave a comment

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: