Add custom add_header directive for CORS

I am trying to add this header
add_header 'Access-Control-Allow-Origin' '*';
for a specific JavaScript file using Trellis templating. To do so I’ve followed these steps:

  1. Created a new template called cors.conf.j2 at the following location: /trellis/nginx-includes/website.com/cors.conf.j2.

The contents of the file are simple:

location /path/to/file.min.js {
  add_header 'Access-Control-Allow-Origin' '*';
}
  1. Deploy the changes
  2. Provision with trellis provision --tags nginx-includes production
  3. SSH into production and confirm that the file has been templated out to /etc/nginx/includes.d/website.com/cors.conf

So far so good. However, when I request the JS file in question, the Access-Control-Allow-Origin header is missing:

$ curl -I https://website.com/path/to/file.min.js

HTTP/2 200
server: nginx
date: Thu, 08 Aug 2024 19:47:17 GMT
content-type: text/javascript
content-length: 33027
last-modified: Fri, 02 Aug 2024 13:39:30 GMT
vary: Accept-Encoding
etag: "66ace192-8103"
expires: Fri, 08 Aug 2025 19:47:17 GMT
cache-control: max-age=31536000
cache-control: immutable
cache-control: public
accept-ranges: bytes

Perhaps the new header directive is being overridden somewhere? I’m not sure how to go about troubleshooting. Anyone managed to add their own CORS headers using nginx-includes?

You can debug whether the location block in question actually matches those requests by using a return directive, e.g. return 444 inside that location block. This excludes potential issues with adding HTTP headers.

1 Like

Thank you for the pointer @strarsis!

I finally realized that my location block was missing the = modifier. Turns out a location block matching a specific file needs that equals sign to force an exact match. I’ve modified the contents of /trellis/nginx-includes/website.com/cors.conf.j2 like so:

location = /path/to/file.min.js {
  add_header "Access-Control-Allow-Origin" "*" always;
}

and now the header is being added as expected.

2 Likes