Redirect www.example.com to example.com with VirtualDocumentRoot

1

0

I have apache configured with VirtualDocumentRoot and it works fine:

UseCanonicalName Off
VirtualDocumentRoot /var/www/%0/app/www

But for each domain currently i need 2 directories:

Here are my application

/var/www/example.com/app/www

The other directory contains only .htaccess with redirection to example.com

/var/www/www.example.com/app/www

My question is: Is there any way i can redirect automatically each www prefixed domain to it's non-www counterpart?

PeterM

Posted 2013-10-25T11:55:11.283

Reputation: 111

Answers

0

Ok, it is very easy to add this kind of redirect, just need to add server-wide Rewrite rule.

My final configuration of virtualhost looks like that

<VirtualHost *:80>
    UseCanonicalName Off
    VirtualDocumentRoot /var/www/%0/app/www
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ http://%1$1 [R=301,L]
    <Directory /var/www/%0/app/www>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>
... other options

PeterM

Posted 2013-10-25T11:55:11.283

Reputation: 111

1

Ok, this is an old question, but since I found it on google, others might end up here as well and why not give those future visitors a different solution to the problem? (although it is technically not a answer to the OPs question since you asked for a redirect, but I think it does solve your problem)

Depending on what you want you can either:

1) Have everything for the domain go to the same directory: example.com www.example.com foo.example.com all go to /var/www/example.com/app/www

<VirtualHost *:80>
    ServerName catch.all
    ServerAlias *
    VirtualDocumentRoot /var/www/%-2.0.%-1.0/app/www
</VirtualHost>

2) Have a directory structure like /var/www/[domain]/[subdomain] Both example.com and www.example.com go to /var/www/example.com/www and shop.example.com will be served from /var/www/example.com/shop

<VirtualHost *:80>
    ServerName sub.domain
    ServerAlias *.*.*
    VirtualDocumentRoot /var/www/%-2.0.%-1.0/%-3
</VirtualHost>

<VirtualHost *:80>
    ServerName bare.domain
    ServerAlias *.*
    VirtualDocumentRoot /var/www/%-2.0.%-1.0/www
</VirtualHost>

Note: the www will be served by the sub.domain rule. And non-existing subdomains will result in a 404.

RemyNL

Posted 2013-10-25T11:55:11.283

Reputation: 111