Search code examples
apachehttp-redirect

Setting up a wildcard subdomain in Apache


Help me configure the following logic: when example.ru is requested, the content from var/www/example.ru should be displayed. When *.example.ru is requested, the content from var/www/subdomain should be displayed (where * represents any subdomain, like admin.example.ru).

I'm trying it like this, but it's not working:

<VirtualHost *:80>
    ServerAdmin support@example.ru
    ServerName example.ru
    ServerAlias *.example.ru
    DocumentRoot /var/www/example.ru

    RewriteEngine On
    RewriteCond %{HTTP_HOST} !=example.ru
    RewriteCond %{HTTP_HOST} ^(.+)\.example\.ru$ [NC]
    RewriteRule ^(.*)$ /var/www/subdomain/$1 [L]

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Solution

  • Just break it up into two virtual hosts and set the DocumentRoot for each of them. No need to use rewrite rules at all.

    <VirtualHost *:80>
        ServerAdmin support@example.ru
        ServerName example.ru
        DocumentRoot /var/www/example.ru
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>
    
    <VirtualHost *:80>
        ServerAdmin support@example.ru
        ServerName sub.example.ru
        ServerAlias *.example.ru
        DocumentRoot /var/www/subdomain
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>