How to Enable CORS in Apache
Cross-Origin Resource Sharing (CORS) is the process, which tells the web browsers to allows resources running form different origins (domain, protocol, or port) via HTTP headers. This tutorial will help you to enable CORS in the Apache webserver.
Prerequsities
You must have enabled Apache headers modules. The Redhat based have default enabled headers modules. For the Ubuntu and Debian, based systems execute the following command to enable headers modules.
a2enmod headers
Enable CORS in Apache
Set Access-Control-Allow-Origin (CORS) authorization to the header in Apache web server. Add the following line inside either the <Directory>, <Location>, <Files> sections under <VirtualHost> in Apache configuration files. You can also place this inside the .htaccess file.
Header set Access-Control-Allow-Origin "*"
Example
To allow Access-Control-Allow-Origin (CORS) authorization for all origin domains for all files inside a directory.
|
1
2
3
4
5
|
<Directory "/path/to/dir">
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
</Directory>
|
To allow Access-Control-Allow-Origin (CORS) authorization for specific files only. For example to allow CORS for fonts only use following example:
|
1
2
3
4
5
|
<FilesMatch "\.(ttf|otf|eot|woff)$">
<IfModule mod_headers.c>
Header Set Access-Control-Allow-Origin "*"
</IfModule>
</FilesMatch>
|
To allow Access-Control-Allow-Origin (CORS) with multiple origin domains, Use following example
|
1
2
3
4
5
6
|
<FilesMatch "\.(ttf|otf|eot|woff)$">
<IfModule mod_headers.c>
SetEnvIf Origin "http(s)?://(www\.)?(google.com|staging.google.com|development.google.com)$" AccessControlAllowOrigin=$0
Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
</IfModule>
</FilesMatch>
|
After making changes in configuration files, You need to restart the Apache webserver. But no need to restart if adding in the .htaccess file.