We earn commission when you buy through affiliate links.
This does not influence our reviews or recommendations.Learn more.
Restrict or allow resource sharing between sites using CORS header.
CORS (Cross-Origin Resource Sharing) header is supported on all modern browsers.
Can I Use cors?Data on support for the cors feature across the major browsers from caniuse.com.
By default, the surfing app restricts cross-origin HTTP requests through scripts.
And,CORScan be handy to reuse the common software resources on other web applications.
Once it is added correctly, it instructs the surfing app to load the system from a different origin.
There are six popular types of CORS headers a server can send.
It supports wildcard (*) and doing so any domain can load the resources.
However, it does have an option to allow a specific origin.
Apache
Add the following inhttpd.confor any other in-use configuration file.
Restart the Apache to test.
You should see them in response headers.
Nginx
Here is an example to allow origin https://geekflare.dev.
Add the following in theserverblock ofnginx.confor in-use configuration file.
Access-Control-Allow-Methods
The web app can initiate one or more HTTP methods to jump into the resources.
After the restart, you should see them in the response headers.
Access-Control-Allow-Headers
The following headers are in safelist means you dont need to add one.
It should work by default.
However, if it’s crucial that you add custom one, you’re able to do it.
It supports one or more headers.
Lets say you want to allowX-Custom-HeaderandX-Powered-Byheaders.
After a restart, you should see the result in response headers.
An example of adding X-Customer-Software and X-My-Custom header.
Access-Control-Expose-Headers
The following headers are already safe list.
Means, you dont need to add if you want to expose them.
Use a wildcard to expose all headers.
The result should look like this.
If you want to exposeOriginheader.
Access-Control-Max-Age
Do you know the data fromAccess-Control-Allow-HeadersandAccess-Control-Allow-Methodsheaders can be cached?
It can be cached for up to 24 hours in Firefox, 2 hours in Chrome (76+).
To block the caching, you’re free to keep the value as-1
To cache for 15 minutes.
As you’ve got the option to see, the value is in seconds.
To cache for one hour.
Once added, restart Nginx to see the results.
You may also be interested in applyingOWASP recommended secure headers.