Apache: How to redirect non-www to www (or vice-versa)

Updated: January 20, 2024 By: Guest Contributor Post a comment

Introduction

Managing redirections is a fundamental skill for web administrators and developers aiming to ensure a smooth browsing experience and maintain SEO rankings. For Apache servers, redirecting traffic from a non-www to a www domain (or vice-versa) is a common task. This article will guide you through the steps necessary to set up this redirection, including explanation of directives, editing configuration files, and troubleshooting.

Before we jump into the practical steps, it’s essential to have an understanding of why such redirection is necessary. Search engines like Google see www.example.com and example.com as two different websites. Consistency in using either the ‘www’ or the ‘non-www’ version of your URL is crucial for optimal search engine rankings. Moreover, redirecting all traffic to one version of your domain ensures that your users have a consistent experience and may help avoid session-related issues in web applications.

Enabling mod_rewrite

The first step is to make sure the mod_rewrite module is enabled on your Apache server. mod_rewrite is a powerful and flexible module that allows for URL rewriting and redirection. You can enable mod_rewrite by executing the following command:

a2enmod rewrite
service apache2 restart

Or, depending on your system, you may need to uncomment the following line in your Apache configuration file (httpd.conf or apache2.conf):

LoadModule rewrite_module modules/mod_rewrite.so

It is also essential to ensure that your server configuration allows .htaccess files to override server configuration settings. This is typically achieved by setting AllowOverride to All for your document root:

<Directory /var/www/html>
    AllowOverride All
</Directory>

Creating and Editing .htaccess File

Once mod_rewrite is enabled, the next step is creating or editing an .htaccess file in your document root directory. Don’t forget to backup your .htaccess file before making changes.

Redirect non-www to www

To redirect all requests from a non-www version of your site to the www version, you can add the following lines to your .htaccess file:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

In this code example, the RewriteCond directive checks if the HTTP_HOST is exactly ‘example.com’ using a regular expression. If this condition is true, then the RewriteRule redirects to the www version of the URL. The flags [L] and [R=301] indicate that this is the last rule to process for this request and that the redirect should be a permanent one (HTTP status code 301), respectively.

Redirect www to non-www

If you prefer to use the non-www version of your domain, you’ll want to ensure that all traffic to the www version is redirected to your root domain. You can accomplish this by adding the following to your .htaccess file:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

This snippet works similarly to the non-www to www redirection, but in reverse. Here, we check if the HTTP_HOST begins with ‘www.example.com’ and rewrite the URL to exclude the ‘www’ prefix.

Testing Your Redirection

After updating the .htaccess file, it’s vital to test your website to ensure the redirection is working as expected. Try accessing both the www and non-www versions of your website and check if the URL in the address bar changes appropriately. If the redirection does not work, ensure that you have cleared your browser’s cache, as it can sometimes retain the old version of your site due to caching.

Troubleshooting Common Issues

Redirection issues may arise due to several factors, such as incorrect configuration settings, conflicts with other rules, or server misconfiguration.

  • Syntax errors: Check that the syntax in your .htaccess file is correct and that you’ve escaped characters like the period that have special meanings in regular expressions.
  • Module activation: Verify that mod_rewrite is indeed enabled on your Apache server.
  • .htaccess overrides: Confirm that your virtual host is configured to allow .htaccess overrides. Otherwise, your redirects won’t take effect.
  • Server configuration: For those managing multiple virtual hosts or server configurations, ensure that the appropriate <VirtualHost> block contains the correct ServerName and ServerAlias directives.
  • Browser cache: As mentioned earlier, your browser cache can interfere with the testing of your redirects. Use your browser’s private browsing or incognito mode to ensure you are seeing the most recent state of your site.

It’s critical to approach troubleshooting methodically, addressing one potential issue at a time. Logs can also be invaluable for pinpointing the source of the problem; error_log and access_log contain details about server requests and errors.

Conclusion

Setting up a redirect from non-www to www or vice-versa on Apache helps maintain consistent branding, improve user experience, and consolidate domain authority for search engine optimization. We’ve covered enabling mod_rewrite, editing your .htaccess file, testing redirects, and troubleshooting common issues. Always test configuration changes in a controlled environment before applying them to your live site, and be sure to backup your configurations before making changes. With careful planning and execution, your site can benefit from a sound redirection strategy.