FeaturedHow-To

How To Allow Multiple CORS Origins in .htaccess

3 Mins read
Unlock Cross-Origin Freedom: Safely Handle Multiple Domains in .htaccess

htaccess Access-Control-Allow-Origin: Enable CORS for Multiple Domains Securely

Cross-Origin Resource Sharing (CORS) is a critical feature of modern web applications that allows web servers to specify which origins can access their resources. This mechanism bypasses the Same-Origin Policy (SOP), which restricts interactions between resources from different origins for security reasons.

The Access-Control-Allow-Origin header plays a pivotal role in CORS by indicating which domains are permitted to access a resource. However, this header does not support listing multiple origins directly, which poses challenges for developers needing to support multiple trusted domains.

In this guide, we’ll explore secure and practical methods to allow multiple origin domains using .htaccess configurations, focusing on Apache servers. We’ll dive into best practices, implementation strategies, and how to avoid common pitfalls.


Understanding CORS and Access-Control-Allow-Origin

Same-Origin Policy and Its Implications

The Same-Origin Policy restricts web pages from making requests to a different domain than the one that served the page. While this improves security, it can limit legitimate use cases, such as API access across subdomains.

The Role of CORS

CORS allows servers to define a flexible access control policy using HTTP headers. When properly configured, CORS enables secure cross-origin requests by validating the Origin header sent by the browser.

Basic Use of Access-Control-Allow-Origin

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

This setup permits only one domain. Trying to include multiple domains like this will not work:

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

Challenges of Multiple Origins

Limitations of Static Configuration

Apache does not support listing multiple origins in a single Access-Control-Allow-Origin header. Only one origin or a wildcard * is allowed.

Security Risks of Wildcard Origins

Using a wildcard (*) permits any domain to access resources:

Header set Access-Control-Allow-Origin "*"

This may expose sensitive data to untrusted sites, especially when credentials are involved.

Common Pitfalls

  • Failing to validate the Origin header
  • Setting the header for every request without conditional logic
  • Ignoring preflight (OPTIONS) requests

Implementing Multiple Origin Support in .htaccess

Using mod_rewrite and Conditional Logic

Apache’s mod_rewrite can be used to inspect the Origin header and dynamically set response headers.

RewriteEngine On
RewriteCond %{HTTP:Origin} ^https://(example\.com|another\.com)$ [NC]
RewriteRule .* - [E=ORIGIN:%{HTTP:Origin}]
Header always set Access-Control-Allow-Origin "%{ORIGIN}e" env=ORIGIN

Validating and Sanitizing the Origin

Make sure to match only known, safe domains using regular expressions. Avoid generic matches like .*.


Using SetEnvIf and Header Directives

A more readable alternative using SetEnvIf:

SetEnvIf Origin "^https://example\.com$" ORIGIN_OK
SetEnvIf Origin "^https://another\.com$" ORIGIN_OK

Header always set Access-Control-Allow-Origin %{Origin}e env=ORIGIN_OK
Header always set Access-Control-Allow-Methods "GET, POST, OPTIONS" env=ORIGIN_OK
Header always set Access-Control-Allow-Headers "Content-Type, Authorization" env=ORIGIN_OK

Handling Preflight Requests

Apache needs to handle OPTIONS method properly for CORS to work:

RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]

Using a Whitelist Approach

A whitelist makes your CORS setup manageable and secure.

<IfModule mod_setenvif.c>
    SetEnvIf Origin "^https://(example\.com|another\.com)$" CORS_ALLOW_ORIGIN
</IfModule>

<IfModule mod_headers.c>
    Header always set Access-Control-Allow-Origin "%{Origin}e" env=CORS_ALLOW_ORIGIN
</IfModule>

Handling Subdomains and Wildcards

Use with caution:

SetEnvIf Origin "^https://(.*\.)?example\.com$" CORS_ALLOW_ORIGIN

This allows all subdomains of example.com.


Security Best Practices

  • Always validate origins. Don’t blindly echo the Origin header.
  • Avoid wildcards for Access-Control-Allow-Origin unless data is truly public.
  • Set explicit headers for Access-Control-Allow-Methods and Access-Control-Allow-Headers.
  • Don’t allow credentials (Access-Control-Allow-Credentials: true) unless absolutely necessary, and never with a wildcard origin.
  • Protect against XSS and CSRF by ensuring your CORS policy only allows trusted origins.

Testing and Debugging

Using Browser DevTools

Check the Network tab in Chrome or Firefox to view request and response headers.

Using curl

curl -i -H "Origin: https://example.com" https://api.yoursite.com/resource

This tests if the correct Access-Control-Allow-Origin is returned.

Debugging Tips

  • Look for missing or incorrect headers.
  • Ensure that preflight requests (OPTIONS) return 200 and expected headers.
  • Check .htaccess syntax and Apache modules (mod_headers, mod_rewrite) are enabled.

Performance Considerations

Impacts of Using .htaccess

.htaccess files are interpreted per request, which can impact performance.

Optimization Tips

  • Move configuration to the main Apache config where possible.
  • Minimize complex regex matching.

When to Use Server-Side Code

If your CORS logic is complex, consider handling it in PHP, Node.js, or another backend language for better control and performance.


Suggested Metadata

  • Title: Allowing Multiple Origin Domains with Access-Control-Allow-Origin in .htaccess
  • Meta Description: Learn how to securely configure Access-Control-Allow-Origin in .htaccess to support multiple CORS origins. Includes examples, security tips, and best practices.
  • Keywords: htaccess multiple origins, Access-Control-Allow-Origin multiple domains, htaccess CORS multiple origins, htaccess allow multiple origins, htaccess whitelist origins, htaccess CORS security, htaccess preflight requests

Conclusion

Enabling support for multiple origin domains in .htaccess requires careful configuration and security mindfulness. By leveraging mod_rewrite, SetEnvIf, and whitelisting techniques, you can create a flexible and secure CORS policy.

Always validate and sanitize the Origin header, avoid wildcard origins unless appropriate, and ensure your server responds correctly to preflight requests.

Test thoroughly, stay informed about best practices, and consult trusted resources like MDN Web Docs and OWASP to strengthen your web security.

Want to dive deeper into web security? Check out our guides on Apache hardening, secure HTTP headers, and more!

Leave a Reply

Your email address will not be published. Required fields are marked *