10

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.

SamSebastien
  • 181
  • 1
  • 3
  • 9

1 Answers1

15

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.
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
  • 2
    This got me to where I needed, the regex needed a bit of tweaking but the concept was right.. The regex that worked was RewriteCond %{HTTP_HOST} ^(?:www\.)?([a-z0-9-]+\.[a-z]+) [NC] – SamSebastien Apr 23 '13 at 22:11
  • just to make clear something that i missed initially: the regex back reference in the RewriteRule is using a '%' not a '$' as usual since '%1' is referring to the first capture group in the RewriteCond. thanks for the answer! – waynedpj Nov 08 '21 at 13:29