How to Set Access-Control-Allow-Origin (CORS) Headers in Apache


Set Access-Control-Allow-Origin (CORS) Headers in Apache

Sometimes, you need to allow access to your website from a different origin (e.g domain or IP address). It is known as Cross Origin Resource Sharing (CORS). By default, it is prohibited in Apache server. This prevents other websites from embedding your resources (CSS, HTML, JS) on their website and loading them from your server. To enable it, you need to set Access-Control-Allow-Origin (CORS) headers in Apache. Let us see how to set Access-Control-Allow-Origin (CORS) headers in Apache Server.

 

How to Set Access-Control-Allow-Origin (CORS) Headers in Apache

Please ensure that you have installed Apache Web Server on your system

 

It’s easy to allow Cross Origin Resource Sharing (CORS) in Apache. Just add the following lines in <Directory>, <Location>, <Files> blocks under <VirtualHost>, in Apache configuration files. You can also add them to the .htaccess file.


Header set Access-Control-Allow-Origin "*"

 

Here are some common use cases

Allow Access-Control-Allow-Origin (CORS) authorization for all files inside a directory

If you want to allow CORS to just all files in one directory (e.g /path/to/dir), add the following code in <Directory> block


<Directory "/path/to/dir">
 <IfModule mod_headers.c>
  Header set Access-Control-Allow-Origin "*"
 </IfModule>
</Directory>

 

Allow Access-Control-Allow-Origin (CORS) authorization for specific file types

If you want to allow CORS to only specific file types like pdf, jpg, font files, paste the following block of code.


<FilesMatch "\.(ttf|otf|eot|woff)$">
 <IfModule mod_headers.c>
  Header Set Access-Control-Allow-Origin "*"
 </IfModule>
</FilesMatch>

 

Allow Access-Control-Allow_origin (CORS) only from specific domains/sub domains

The above commands allow Cross Origin Requests from all domains. However, if you only want to support requests from specific domains & sub domains (e.g google.com, facebook.com) then you can add the following block of code.


<FilesMatch "\.(ttf|otf|eot|woff)$">
 <IfModule mod_headers.c>
  SetEnvIf Origin "http(s)?://(www\.)?(google.com|facebook.com)$" AccessControlAllowOrigin=$0
  Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
 </IfModule>
</FilesMatch>

 

Remember to restart Apache Server to apply the changes.

 

$ sudo systemctl restart apache2 [Ubuntu/Debian]
$ sudo systemctl restart httpd [RHEL/CentOS]

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!