How to properly setup nginx Access-Control-Allow-Origin into response header based on the Origin header from the request? How to properly setup nginx Access-Control-Allow-Origin into response header based on the Origin header from the request? nginx nginx

How to properly setup nginx Access-Control-Allow-Origin into response header based on the Origin header from the request?


Using if can sometimes break other config such as try_files. You can end up with unexpected 404s.

Use map instead

map $http_origin $cors_header {    default "";    "~^https?://[^/]+\.example\.com(:[0-9]+)?$" "$http_origin";}server {    ...    location / {        add_header Access-Control-Allow-Origin $cors_header;        try_files $uri $uri/ /index.php;    }    ... }

If is evil


I'm starting to use this myself, and this is the line in my current Nginx configuration:

add_header 'Access-Control-Allow-Origin' "$http_origin";

This sets a header to allow the origin of the request as the only allowed origin. So where ever you are coming from is the only place allowed. So it shouldn't be much different than allowing "*" but it looks more specific from the browser's perspective.

Additionally you can use conditional logic in your Nginx config to specify a whitelist of hostnames to allow. Here's an example from https://gist.github.com/Ry4an/6195025

if ($http_origin ~* (whitelist\.address\.one|whitelist\.address\.two)$) {  add_header Access-Control-Allow-Origin "$http_origin";}

I plan to try this technique in my own server to whitelist the allowed domains.