Cross Origin Resource Sharing (CORS) allows your web server to accept and serve requests from other domains. By default, CORS is disabled in Apache. You need to set Access-Control-Allow-Origin Header to enable CORS in Apache. Here’s how to set Access-Control-Allow-Origin header in Apache.
How to Set Access-Control-Allow-Origin (CORS) Headers in Apache
Here are the steps to set Access-Control-Allow-Origin header in Apache.
1. Open Apache Configuration File
You can enable CORS in Apache by modifying Apache Server configuration file, or .htaccess file.
Using Apache Server Configuration File
If you have access to Apache server configuration file, open it in a text editor. Apache configuration file is located at any of the following locations, depending on your installation
$ sudo vi /etc/apache2/httpd.conf
Using .htaccess file
If you don’t have access to Apache server configuration file, open .htaccess file in a text editor.
$ sudo vi /var/www/html/.htaccess
Bonus Read : How to Install Apache mod_security in Ubuntu
2. Enable CORS in Apache
To set Access-Control-Allow-Origin header in Apache, just add the following line inside either the
<VirtualHost> sections of your file.
Header set Access-Control-Allow-Origin "*"
The above line will allow Apache to accept requests from all other domains. If you only want to accept CORS requests from specific domain (example.com), then use that domain instead of using * above.
Header set Access-Control-Allow-Origin "example.com"
Bonus Read : How to Generate CSR for SSL Certificate in Linux
3. Test Apache Configuration
Test Apache configuration to ensure that there are no errors.
$ sudo apachectl -t
Bonus Read : How to Install SSL Certificate on Apache Windows
4. Restart Apache Server
If you see no errors in previous steps, restart Apache web server
$ sudo systemctl restart apache2
Now your Apache web server will automatically server requests from other domains.