How to Enable CORS in Apache Web Server?

Cross-Origin Resource Sharing(CORS) is a security feature that allows web browsers to make requests to a different domain than the one serving the web page. without CORS, browsers restrict such requests due to security concerns. Enabling CORS ensures that your web server responds correctly to cross-origin requests.

Steps to Enable CORS in Apache web server

1. Enable Apache Headers Module

To enable CORS in Apache, we’ll use the headers module. Follow these steps:

1. Open your httpd.conf file. The location of this file depends on your Apache installation:

On Ubuntu: /etc/apache2/httpd.conf
On CentOS 6: /etc/httpd/conf/httpd.conf
On Windows :C:\Apache24\conf\httpd.conf

2. Verify that the headers module is loaded. Look for the following line:

LoadModule headers_module modules/mod_headers.so

headers module

2. Enabling CORS in Apache

Let’s now configure CORS by updating your Apache configuration with the required headers. These directives can be added to your configuration file in the <Directory>, <Location>, <Files>, or <VirtualHost> sections.

1. Open your httpd.conf or any other relevant configuration file.

2. Add the following lines to allow cross-origin requests from any domain:

<IfModule mod_headers.c>
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "*"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
</IfModule>
  • Requests from any origin are accepted in the first line (*). If necessary, you can substitute particular domains for *.
  • In requests, the second line permits all headers.
  • The permitted HTTP methods are listed in the third line.

3. Restart Apache Service

Restarting the Apache service will allow the modifications you made to take effect.

C:\Windows\System32>httpd -k restart

4. Test Your CORS Configuration

Make a straightforward HTML page using JavaScript that sends cross-origin requests to your Apache server to confirm that CORS is functioning properly. To look for any issues connected to CORS, use the developer console in your browser.

Practical Implementation

Create a sample HTML file (index.html) and test CORS:

1. Create a new directory in your Apache document root (e.g., C:\Apache24\htdocs\cors-demo).

2. Inside this directory, create an index.html file with the following content:

<!DOCTYPE html>
<html>
<head>
<title>CORS Demo</title>
</head>
<body>
<h1>CORS Demo</h1>
<script>
fetch('http://localhost/api/data')//make sure to give correct api endpoint url for fetching
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error fetching data:', error));
</script>
</body>
</html>

3. Replace the URL in the fetch call with your actual API endpoint.

4. Access http://localhost/cors-demo/index.html in your browser. Open the developer console to check for CORS-related messages.