velizarn
By:
velizarn

How to redirect all requests to http(s)://www.domainname.tld/

December 14, 2015 1.1k views
Apache LAMP Stack Configuration Management System Tools CentOS

Hello,

I want to setup my Apache 2.4 server in a way to redirect all requests in following way:

http://domainname.tld/ to http://www.domainname.tld/
and
https://domainname.tld/ to https://www.domainname.tld/

my vhost conf file is as follows:

<VirtualHost *:80>

    ServerName www.domainname.tld

    ServerAlias www.domainname.tld

    DocumentRoot ......

    # other vhost settings
    # ...
    # ...
    # ...

</VirtualHost>

<VirtualHost *:80>
    ServerName domainname.tld
    ServerAlias domainname.tld
    Redirect "/" "http://www.domainname.tld/"
</VirtualHost>

<VirtualHost *:443>

    ServerName www.domainname.tld

    ServerAlias www.domainname.tld

    DocumentRoot /..............

    # SSL configuration
    # ...
    # ...
    # ...

</VirtualHost>

<VirtualHost *:443>
    ServerName domainname.tld
    ServerAlias domainname.tld
    Redirect "/" "https://www.domainname.tld/"
</VirtualHost>

I don't have any rewrite rules in my htaccess file.

http redirect works ok, but if i open https://domainname.tld my request is redirected to the very first vhost configuration on my server.

Please can you tell me what's wrong with my vhost configuration?

As far as I know the best way to achieve this type of redirect is to modify the vhost configuration instead of adding rewrite rules to the htaccess file.
The very best way to solve this doesn't involve mod_rewrite at all, but rather uses the Redirect directive placed in a virtual host for the non-canonical hostname(s).

Please share your comments!
Thank you in advance!

1 Answer

This article explains the solution for my question:

How To Avoid SSL Certificate Mismatch Errors When Redirecting Multiple Virtual Hosts - Because the SSL protocol encapsulates HTTP traffic, adding or removing the 'www' subdomain must be done correctly.

https://www.tombrossman.com/blog/2014/avoid-certificate-mismatch-when-redirecting-multiple-ssl-virtualhosts/

<VirtualHost :443>
    ServerName EXAMPLE-1.com
    SSLEngine on
    SSLCertificateFile      /PATH/TO/CERT.crt
    SSLCertificateChainFile /PATH/TO/CHAIN/FILE.pem
    SSLCertificateKeyFile   /PATH/TO/KEY.key
    RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</VirtualHost>

<VirtualHost :443>
    ServerName WWW.EXAMPLE-1.com
    ...
</VirtualHost>

All you need to do is add the certificate paths inside the redirect block so the key exchange can take place prior to the redirect.

Have another answer? Share your knowledge.