Search code examples
.htaccessmod-rewrite

htaccess get domain name from %{HTTP_HOST} into variable, minus the www


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.


Solution

  • 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]
    
    • Here we have a $1, which takes the capture group from the RewriteRule pattern foo/(.+).
    • And we have a %1, which takes the capture group from the previous RewriteCond (?:www\.)?(.+).
      Note that (?:...) is a non-capturing group. This is why we use %1 instead of %2.