Impaloo
By:
Impaloo

Redirect domain.com to www.domain.com

September 3, 2014 5.9k views

Hey. I'm trying to implement a permanent redirect from domain.com to www.domain.com.

This is how my .conf file looks like.

/etc/apache2/sites-available/domain.com.conf

<VirtualHost *:80 *:443>
        ServerName www.domain.com
        ServerAdmin william@domain.com

        DocumentRoot /var/www/domain.com/public_html

        ErrorLog /var/www/domain.com/logs/error.log
        CustomLog /var/www/domain.com/logs/access.log combined
</VirtualHost>

<VirtualHost *:80>
        ServerName domain.com
        Redirect permanent / http://www.domain.com
</VirtualHost>
<VirtualHost *:443>
        ServerName domain.com
        Redirect permanent / https://www.domain.com
</VirtualHost>

This doesn't work. It works if I want to achieve the opposite (www.domain.com to domain.com) however - obviously after changing a few things.

5 comments
  • At first blush, that looks correct. When you say it doesn't work do you mean it doesn't redirect of it leads to an error?

  • @asb Visiting domain.com will use the 000-default.conf configuration. Visiting www.domain.com returns an "Unknown host" error, but that might be due to my DNS settings.

    Still.. visiting domain.com should not default to the 000-default.conf config, it should be resolved in domain.com.conf, right?

  • It sounds like you have overlapping things in 000-default.conf and domain.com.conf

  • My 000-default.conf file looks like this.

    <VirtualHost *:80>
            ServerAdmin william@domain.com
            DocumentRoot /var/www/default/public_html
    
            ErrorLog ${APACHE_LOG_DIR}/error.log
            CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>
    
  • @asb I tried removing the symlinked 000-default.conf in sites-enabled/. Now it works as expected.

    This seems really weird.. doesn't it "need" to be there to ensure a default behaviour?

1 Answer

You can set up an CNAME record through the DigitalOcean DNS panel. To add a CNAME record, first click on the domain that you'd like to edit

Once you've done that, click the Add Record button

From there, select the CNAME Record button and enter a name for the record. The CNAME records point to a site's canonical name. When entering your CNAME record, enter what you need the record to look up in the Name field, and then add the record it resolves to in the Hostname field.

In Name: www
In Hostname: @

and this will do the work

www.domain.com

  • So I've done those steps, and it's not redirecting. It just times out. My site won't let me access it unless I type in www. before the domain. It won't even work if I add http:// ... :(

Have another answer? Share your knowledge.