Typically, web browsers do not allow requests from a one domain to another. So if your website is example.com, it won’t allow users on another website example2.com to send requests to example.com. It will only support requests sent to example2.com. However, sometimes, you may need to allow requests from a different domain. This can be accomplished by setting Access-Control-Allow-Origin header. It is also know as Cross Origin Resource Sharing (CORS).
How to Allow Access-Control-Allow-Origin using .htaccess
Here are the steps to allow access-control-allow-origin using .htaccess file in Apache web server.
Before you proceed, please ensure you have enabled .htaccess (mod_rewrite) in Apache. Here are the steps to do it:
Place your .htaccess file in the root document folder of your website (/var/www/html)
After that, follow these steps
1. Enable mod_headers
Open a terminal session or SSH into your Linux system and run the following command
$ sudo a2enmod headers
2. Open .htacces file
Open .htaccess file in a text editor
$ sudo vim /var/www/html/.htaccess
3. Allow Access-Control-Allow-Origin
Allow cross-origin requests by adding the following lines
<IfModule mod_headers.c> Header set Access-Control-Allow-Origin "*" </IfModule>
The above code will accept requests from all websites. If you only want to accept requests from a specific website, you can mention its domain (e.g example2.com) instead of ‘*’.
<IfModule mod_headers.c> Header set Access-Control-Allow-Origin "http://example2.com" </IfModule>
4. Restart Apache Web Server
Restart Apache web server to apply changes
$ sudo /etc/init.d/apache2 start [Debian or Ubuntu] # sudo apachectl restart [RHEL, CentOS or Fedora]
That’s it! Now Apache will accept requests from other websites (origins) too.