Nginx – How to dynamically add Access-Control-Allow-Origin rules with the help of the referrer

nginx

I have a couple of unforeseeable domain referrers which I want to allow get resources from my servers and also allowing to set credentials.

I know that this is kind of stupit to work against the security features of W3C but I can't add all domains every time a new domans wants to do a request for a ressource.

So what i have so far is a location block where I add a header like this:

add_header 'Access-Control-Allow-Origin' $http_referer;

This works great. Almost. When the request does request the Nginx the referrer is always showing up with tailing slash. Which in fact isn't the truth and the domain can't grab the resource.
Example looks like this.
in url is: http://example.com
nginx shows that $http_referer is http://example.com/ so resource is not allowed to access because http://example.com is not http://example.com/

How can I replace the referrer the right way and omit the tailing slash where there is no…? There are also probably more complex referrers with path etc…

Best Answer

One solution is to use the nginx map feature. In the HTTP level, you define the map:

map $http_referer $alloworigin {
    ^(.+)/$ $1;
    ^(.+)[^/]$ $1;
    default "";
}

And then for add_header you use the following:

add_header 'Access-Control-Allow-Origin' $alloworigin;

Here the map transforms $http_referer to $alloworigin variable as follows:

  1. If $http_referer contains at least one character and ends with /, the / is removed.
  2. If $http_referer contains at least one character and does not end with /, the whole string is copied.
  3. If there is no $http_referer or it is empty, $alloworigin is empty.

The numbers above correspond to the map lines.