Trying to tidy up .htaccess and remove hard-coding of domain name

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]

js,

It looks to me like you’re trying to make this too hard! I have examples of forcing https (and the reverse) in my signature’s tutorial which completely ignore the domain name (uses internal redirects except for https:// redirections where it uses %{HTTP_HOST} - but better to ensure that the www’d or non-www’d version is used to meet your certificate’s specifications.

Regards,

DK

Thanks for the response.

Is the Apache HTTP_HOST variable secure? Is there any way it could be manipulated by a hacker?

Also, would it be better to use SERVER_NAME (assuming the variable is set to the Apache config)?