Adding custom headers to a file or a location

in Nginx configuration

To add a certain HTTP header to a file, create a server.headers file in /data/web/nginx, containing the following snippet:

location /info.html {
  add_header "Some Header Name" "Some value";
}

If you want to do the same using a regex of all files that should have this additional header, that’s possible too:

location ~* (.+\.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt))$ {
  add_header Pragma public;
  add_header Cache-Control "public";
}

Or even on all files:

  add_header Pragma public;

If you want to override the /media/ location, you must use an other regex then the already defined location block in our Magento Nginx config in /etc/nginx/magento1.conf:

location ~ ^/media/ {
location ~ \.php$ {
return 403;
}
try_files $uri $uri/ =404;
expires 30d;
}

Use the following in the /data/web/nginx/server.headers configuration file and don’t forget to change the domain name:

location ~* ^/media/.*\.(css|js|png|gif|txt)$ {    
add_header Access-Control-Allow-Origin "https://www.example.com";
}

You could add more file extensions if you want.

Keep in mind

  • It is not possible in Nginx to add locations twice. Only the first location in the configuration file takes presence. This is because Nginx config works on a per request base.
  • Don’t use a colon (:) when adding headers. This will result in inconsistent results in different browsers.

0