How to add CORS into virtualhost in Apache? Let’s find the solution with this article. Bobcares, as a part of our Server Management Services, offers solutions to every query that comes our way.
How to add CORS into virtualhost in Apache?
Cross-Origin Resource Sharing or CORS is a method that instructs web browsers to allow resources from different origins to run using HTTP headers. It also makes use of a mechanism that allows browsers to send a “preflight” request to the server hosting the cross-origin resource. This is to ensure that the server will allow the actual request. The browser sends headers indicating the HTTP method and headers. This will be used in the actual request during that preflight.
Cross-domain connections are not active by default in the Apache web server.
Steps
- Firstly, we need to enable the Apache headers modules. We can use the below codes:
For Ubuntu/Debian:
$ sudo a2enmod headers
For CentOS/Redhat/Fedora:
LoadModule headers_module modules/mod_headers.so
- Then we can add it to a virtual host in Apache. If we add it to the virtual host configuration file, then it will be enabled for only that file’s website.
<VirtualHost *:443> ... Header add Access-Control-Allow-Origin "*" ... </VirtualHost>
- Finally, we must restart the server.
Configurations to add CORS in Apache
1. From all websites: If we want to accept cross-domain requests from all websites, use the below code:
Header add Access-Control-Allow-Origin *;
2. From a single domain: We must include the domain in place of the wildcard character * to enable CORS for one website domain.
Header add Access-Control-Allow-Origin "example.com";
3. From multiple domains: We should provide each domain one after another to add CORS from multiple sites.
Header add Access-Control-Allow-Origin "example1.com"; Header add Access-Control-Allow-Origin "example2.com";
4. From localhost: Replace the domain name with 127.0.0.1 or localhost to enable CORS from localhost.
Header add Access-Control-Allow-Origin "localhost";
[Looking for a solution to another query? We are just a click away.]
Conclusion
In this post, we include a simple solution from our Tech team to add CORS into virtualhost in Apache.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
var google_conversion_label = "owonCMyG5nEQ0aD71QM";
0 Comments