Enabling mod_headers and CORS with Apache2

I’ve been working on a project and wanted to test out accessing media from a different domain using CORS.

There’s two steps to this.

  1. Make sure you have Apache mod_headers enabled. Use apachectl -M on the command line interface and review the results. It should include something like this: headers_module (shared). If not then run this to enable it a2enmod headers. It will then tell you to restart apache with service apache2 restart.
  2. Add these lines to your .htaccess file. WARNING! The .htaccess file is very touchy! Any syntax error and it will make your site completely inaccessible! Here be dragons! That being said, if you’re careful, do this at a time your site has low use, and keep a backup learning how to use .htaccess is very handy.
<IfModule mod_headers.c>
  <FilesMatch "\.(mp3)$">
    Header set Access-Control-Allow-Origin "http://localhost:3000"
  </FilesMatch>
</IfModule>

The above will allow any mp3 to be accessed when coming from http://localhost:3000. You could set this to another domain you have files stored at.

There is much more which can be done with this but for my current testing purposes this did the trick.

Here’s some more details:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers

Leave a Reply

Your email address will not be published. Required fields are marked *