W3docs

enable cors in .htaccess

To enable Cross-Origin Resource Sharing (CORS) in an .htaccess file, you can add the following lines:

To enable Cross-Origin Resource Sharing (CORS) in an .htaccess file, you can add the following lines:

Example of enabling Cross-Origin Resource Sharing (CORS) in an .htaccess file

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers "Content-Type"

This will allow any origin to access resources on your server, using any method and any Content-Type.

You can also specify a particular origin by replacing the * with the URL of the origin. For example:

Example of enabling Cross-Origin Resource Sharing (CORS) with specifying a particular origin in an .htaccess file

Header set Access-Control-Allow-Origin "https://example.com"

This will allow https://example.com to access resources on your server, but block all other origins.

The Access-Control-Allow-Origin header does not support comma-separated multiple origins. To allow multiple specific origins, you must use conditional logic to check the request's Origin header and set the response header dynamically. For example:

Example of enabling Cross-Origin Resource Sharing (CORS) with specifying multiple origins in an .htaccess file

SetEnvIf Origin "^https://(www\.)?(example\.com|othersite\.com)$" CORS_ALLOW_ORIGIN=$0
Header set Access-Control-Allow-Origin %{CORS_ALLOW_ORIGIN}e env=CORS_ALLOW_ORIGIN

This will allow https://example.com and https://othersite.com to access resources on your server, but block all other origins.

Note that the mod_headers Apache module must be enabled for these directives to work. Additionally, the .htaccess file must be located in the same directory as the resources that you want to allow CORS for, or in a parent directory.

For full CORS compliance, especially when using custom headers or methods, you should also handle OPTIONS preflight requests. You can add the following to return a 204 No Content response for preflight requests:

RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^ - [R=204,L]