Cross-Origin Resource Sharing (CORS) is a mechanism that allows web servers to specify which external domains are permitted to access their resources. Configuring CORS is essential for ensuring proper communication between your web server and external origins while maintaining security. This article will guide you through adding a CORS policy to your .htaccess file.
What Is CORS?
CORS enables a browser to securely request resources from a domain different from the one that served the initial web page. For example, if your website hosted on example.com needs to access resources from api.example2.com, a proper CORS policy must be in place. Without it, the browser will block the request for security reasons.
Adding a CORS Policy to .htaccess
Follow these steps to enable CORS by editing your .htaccess file:
Step 1:
Open your .htaccess file. See How-to edit your .htaccess file
Step 2:
Add the following CORS policy to your .htaccess. Replace the https://example.com with a specific domain you wish to allow access from.
# Enable Cross-Origin Resource Sharing (CORS) for a specific domain
# Only the domain "https://example.com" is allowed to access the resources.
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "https://example.com"
</IfModule>
For example, if your website is example.com and you wish to allow access to resources from both example.com and www.example.com add the following to your .htaccess file:
# Enable Cross-Origin Resource Sharing (CORS) for a specific domain
# Both the domain "https://example.com" is allowed to access the resources.
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "https://example.com"
Header set Access-Control-Allow-Origin "https://www.example.com"
</IfModule>
Step 4:
Save the .htaccess file and test your CORS policy by making requests from the specified origins and checking the browser’s developer tools for any CORS-related errors.
Best Practices for CORS Configuration
- Avoid using * for Access-Control-Allow-Origin in production environments. Restrict access to trusted domains for better security.
- Test your CORS policy thoroughly to prevent accidental exposure of sensitive resources.
- Regularly review and update your policy as required.