Cairo
Cairo

Reputation: 341

.htaccess - how to set headers dynamically per domain?

I'm trying to get CORS functioning with multiple domains.

    Header add Access-Control-Allow-Origin "http://localhost, http://multiplay.io"

However, it seems that most browsers only support one domain. I've been told that the solution is to set the header per incoming domain.

How do you do this using the .htaccess file?

Upvotes: 2

Views: 2182

Answers (2)

Muhammad Reda
Muhammad Reda

Reputation: 27043

You can make use of IF, ELSEIF, ELSE directives if you are on Apache 2.4+.

# if production
<If "req('Host') == 'multiplay.io'">
  Header add Access-Control-Allow-Origin http://multiplay.io
</If>

# if localhost
<ElseIf "req('Host') == 'localhost'">
  Header add Access-Control-Allow-Origin http://localhost
</ElseIf>

# if not either
<Else>
</Else>

Upvotes: 0

Trott
Trott

Reputation: 70095

If it's only two values you wish to alternate between, you can use SetEnvIf to differentiate between the two.

SetEnvIf Referer "^http://localhost/" is_localhost
Header add Access-Control-Allow-Origin http://localhost env=is_localhost
Header add Access-Control-Allow-Origin http://multiplay.io env!=is_localhost

There may be a more elegant solution, but something like the above (untested) directives should work.

(Note that it is trivial to forge a Referer header, so be aware of the security implications of forged Referer headers when using Referer headers for pretty much anything.)

Additionally, if you just want to allow all hosts, you can specify * instead of listing multiple hostnames:

Header add Access-Control-Allow-Origin *

But I assume you already knew that and don't want to be that permissive.

Upvotes: 4

Related Questions