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.
- Make sure you have Apache
mod_headers
enabled. Useapachectl -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 ita2enmod headers
. It will then tell you to restart apache withservice apache2 restart
. - 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