Skip to main content

.htaccess Cross-origin Resources

.htaccess Cross-origin Resources

In .htaccess, there are directives that allow you to control CORS (Cross-Origin Resource Sharing) access to server resources.

note

CORS is an HTTP-header based mechanism that allows a server to indicate the external origins (domain, protocol, or port) which a browser should permit loading of resources.

For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts.

For example, using the same-origin policy, a web application can only request resources from the same origin the application was loaded from (unless the response from other origins includes the appropriate CORS headers).

General CORS access

This directive will add the CORS header for all resources in the directory from any website.

<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
note

In this example, any requests from external servers will be honored.

For real-world applications, it is unlikely to be what you want.

An alternative is to explicitly define what domains have access to the content of your site.

In the following example, the access is restricted to a subdomain of a main site (example.com).

<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "subdomain.example.com"
</IfModule>
note

This is a safer solution and it is the one that is often adopted in real-world applications.

Cross-origin images

Allowing cross-origin use of images and canvas can lead to fingerprinting attacks.

To mitigate the possibility of these attacks, you should use the crossorigin attribute in the images you request and the code snippet below in your .htaccess to set the CORS header from the server.

<IfModule mod_setenvif.c>
<IfModule mod_headers.c>
<FilesMatch "\.(bmp|cur|gif|ico|jpe?g|a?png|svgz?|webp|heic|heif|avif)$">
SetEnvIf Origin ":" IS_CORS
Header set Access-Control-Allow-Origin "*" env=*IS_CORS*
</FilesMatch>
</IfModule>
</IfModule>
note

The same thing happens to fonts. So, you can also do:

<IfModule mod_headers.c>
<FilesMatch "\.(eot|otf|tt[cf]|woff2?)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>

Cross-origin resource timing

The Resource Timing Level 1 specification defines an interface for web applications to access the complete timing information for resources in a document.

The Timing-Allow-Origin response header specifies origins that are allowed to see values of attributes retrieved via features of the Resource Timing API, which would otherwise be reported as zero due to cross-origin restrictions.

If a resource isn't served with a Timing-Allow-Origin or if the header does not include the origin making the request some of the attributes of the PerformanceResourceTiming object will be set to zero.

<IfModule mod_headers.c>
Header set Timing-Allow-Origin: "*"
</IfModule>