I currently have the following in a htaccess file which redirects certain requests to the requested domain's individual folder if the file does not exist in the root..
RewriteRule ^contact/?$ ASSETS/%{HTTP_HOST}/contact.php
RewriteCond %{REQUEST_URI} !^/ASSETS/%{HTTP_HOST}/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /ASSETS/%{HTTP_HOST}/$1
RewriteCond %{HTTP_HOST} ^(www.)?%{HTTP_HOST}$
RewriteRule ^(/)?$ ASSETS/%{HTTP_HOST}/index.php [L]
Which works fine when my domain folders are named like /ASSETS/www.domain1.com, /ASSETS/www.domain2.com etc
However, I've built a lot of my code already with the assumption that the folders will be labeled /ASSETS/domain1.com etc (domain name, minus the www.)
I'm thinking there is a way to get the domain name from %{HTTP_HOST} into a new variable and strip out the www. part (like an str_replace or something), but all the answers I have found are around a basic redirect all to www. or no www. which isn't going to work as I still want users to access the site from the forced www. version.
I was previously running the rules for each domain individually with a RewriteCond %{HTTP_HOST} ^(www.)?domain1.com$ but there are so many domains now, it's not feasible to do it for each one.
Hope you can help! Thanks in advance.
You can capture the needed host part with a RewriteCond
and use it as %1
in the RewriteRule
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^$ ASSETS/%1/index.php [L]
An alternative solution at the file system level (without htaccess) might be symbolic links. Instead of extracting the necessary host part, have symbolic links to the real directory, e.g.
- ASSETS -+-domain1.com (directory)
|
+-www.domain1.com -> domain1.com (symbolic link)
|
+-domain2.com (directory)
|
+-www.domain2.com -> domain2.com (symbolic link)
To illustrate the different back references, see another example
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^foo/(.+)$ $1/%1/index.php [L]
$1
, which takes the capture group from the RewriteRule pattern foo/(.+)
.%1
, which takes the capture group from the previous RewriteCond (?:www\.)?(.+)
.(?:...)
is a non-capturing group. This is why we use %1
instead of %2
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With