Allow both HTTP and HTTPS and multi domain in CORS header on nginx

Revision history
Tags: cors nginx

Wanted to allow both HTTP and HTTPS to POST to the API of an old solution I’ve been maintaining lately. But the Access-Control-Allow-Origin only allows a single domain with strict scheme. This made me look around in the nginx docs again.

Since my site is also answering on multiple domains, this is pretty neat:

server_name example.com www.example.com;
location /api/ {
    add_header Access-Control-Allow-Origin "${scheme}://${server_name}";
    proxy_pass http://localhost:4242/;
}

References

If you have any comments or feedback, please send me an e-mail. (stig at stigok dotcom).

Did you find any typos, incorrect information, or have something to add? Then please propose a change to this post.

Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.