I think what I need here is SetEnvIf
But, AFAIK, you cannot use environment variables in the DocumentRoot
and <Directory>
directives. (And you can't Define
variables to a calculated/dynamic string using a regex.)
DocumentRoot /home/user/htdocs/${SITE}
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/\.well\-known/acme\-challenge/
RewriteRule ^ https://${SITE}%{REQUEST_URI} [NE,R=301,L]
<Directory /home/user/htdocs/${SITE}>
You could instead define a VirtualDocumentRoot
and use an appropriate regex in the mod_rewrite directives and <DirectoryMatch>
container.
For example, assuming all your domains are of the form <name>.<tld>
then try the following instead of the above subset of directives:
VirtualDocumentRoot "/home/user/htdocs/%-2.0.%-1.0"
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+?)\.?$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [NE,R=301,L]
<DirectoryMatch "/home/user/htdocs/[^.]+\.com">
The %-2.0.%-1.0
part of the VirtualDocumentRoot
directive captures the domain name and TLD (the last 2 parts) from the requested hostname. Importantly, this excludes an optional www subdomain (3rd part from the right).
The %1
backreference in the RewriteRule
substitution string references the part of the hostname less the optional www.
prefix (subdomain) captured in the preceding CondPattern. (This also excludes the trailing dot in the case of a FQDN.)
The <DirectoryMatch>
directive allows access to any directory that is of the form /home/user/htdocs/<example>.com
.
Reference: