Question

I have the below configurations set up in a .htaccess file.

Instead of hard-coding the domain name (domain.com), can I use the domain of the current request and prevent hard-coding of the domain name?

Also, is that safe? Hard-coding guarantees the correct domain of course, but I'm trying to think if the 'grab current domain name' method might cause other issues (especially with the first two examples below).

# Allow cross-domain requests
#
SetEnvIf Origin "^http(s)?://(.+\.)?(domain\.com)$" origin_is=$0
Header add Access-Control-Allow-Origin %{origin_is}e env=origin_is
Header add Access-Control-Allow-Credentials: true

# CSP
#
Header set Content-Security-Policy "default-src 'none'; connect-src http://domain.com https://domain.com;"

# Set domain name as a variable
#
RewriteRule .* - [E=domain_name:domain.com] 

# Redirect non-secure (HTTP) traffic to secure (HTTPS)
#
RewriteCond %{ENV:HTTPS} !on [NC]
RewriteRule ^(.*)$ https://%{ENV:domain_name}/$1 [R=301,L]
Was it helpful?

Solution

You can just use %{HTTP_HOST} env variable which is already populated by Apache.

RewriteCond %{ENV:HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top