1

I have the following virtual hosts:

<VirtualHost *:443>
  ServerName article.example.com
  AliasMatch "^/(.*)" "/var/www/html/article.php"
 </VirtualHost>
 <VirtualHost *:443>
  ServerName company.example.com
  AliasMatch "^/(.*)" "/var/www/html/company.php"
 </VirtualHost>

I would like to put everything under one virtual host like so:

 <VirtualHost *:443>
  ServerName example.com
  ServerAlias *.example.*
  AliasMatch "^(article|company)\.example\.*/(.*)" "/var/www/html/$1.php"
 </VirtualHost>

Is this possible? Do I have to use mod rewrite? I want map certain subdomains to related files on my server without changing the url. I want article.example.com/test-article to map to article.php.

1 Answer 1

1
AliasMatch "^(article|company)\.example\.*/(.*)" "/var/www/html/$1.php"

The AliasMatch directive matches against the requested URL-path (as you are doing in the first example), not the hostname (as you are trying to do here), so something like this will not match.

The obvious choice would be mod_rewrite, as you suggest. For example:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^(article|company)\.
RewriteRule ^ /var/www/html/%1.php [L]

Where the %1 backreference contains the match from the captured subpattern in the preceding CondPattern.

If /var/www/html is the document root, then that can be omitted from the substitution string, rewriting to a document root-relative URL-path instead of an absolute file-path. ie. simply /%1.php.

You could make it more generic and rewrite the request for any subdomain where that subdomain exists as a .php file in the document root. For example:

RewriteCond %{HTTP_HOST} ^([^.]+)\.example
RewriteCond %{DOCUMENT_ROOT}/%1.php -f
RewriteRule ^ /%1.php [L]
2
  • Just trying to understand, so %1 takes the variables from the brackets? Also, why is ^ needed within the RewriteRule? Does the ^ take the string from the condition? Or is ^ just reference the entire string.
    – Maciek
    Aug 30 at 1:36
  • 1
    @MaciekSemik Yes, %1 contains what is matched by the regex in the brackets, in the preceding condition (CondPattern). In the same way $1 would contain what is matched by a bracketed subpattern in the RewriteRule pattern (just like AliasMatch). ^ matches against the requested URL-path - ^ is successful for everything (since we are rewriting every URL-path) - we do not need to actually match anything here. You could use $ or . here instead, but ^ is my preference. eg. In your AliasMatch directive, you could have used ^ instead of "^/(.*)", which is more efficient.
    – MrWhite
    Aug 30 at 1:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .