Tutorial

How To Redirect www to Non-www with Apache on Ubuntu 14.04

Published on May 4, 2015
How To Redirect www to Non-www with Apache on Ubuntu 14.04
Not using Ubuntu 14.04?Choose a different version or distribution.
Ubuntu 14.04

Introduction

When you have your web site or application up and running behind a domain, it is often desirable to also allow your users access to it via the plain domain name and the www subdomain. That is, they should be able to visit your domain with or without the “www.” prefix, e.g. example.com or www.example.com, in a web browser, and be presented with the same content. While there are a variety of ways to set this up, the best solution, for consistency and SEO considerations, is to choose which domain you prefer, plain or www, and redirect the other one to the preferred domain. This type of redirect is called a Permanent Redirect, or “301 redirect”, and can be easily set up by properly configuring your DNS resource records and web server software.

This tutorial will show you how to redirect a www URL to non-www, e.g. www.example.com to example.com, with Apache on Ubuntu 14.04. We will also show you how to redirect in the other direction, from a non-www URL to www. The CentOS 7 version of this tutorial is available here.

If you want to perform this type of redirect with Nginx as your web server, you should follow this tutorial instead: How to Redirect www to non-www with Nginx on Ubuntu 14.04.

Prerequisites

This tutorial assumes that you have superuser privileges, i.e. sudo or root, on the server that is running Apache. If you don’t already have that set up, follow this tutorial: Initial Server Setup on Ubuntu 14.04.

It is assumed that you have Apache installed. If you do not already have this set up, there are several tutorials on the subject under the Apache tag.

You must be able to add records to the DNS that is managing your domain. If you do not already have a domain, you may purchase one from a domain registrar, and manage it with the registrar’s DNS or DigitalOcean’s DNS. In this tutorial, we will use the DigitalOcean DNS to create the necessary records.

Let’s get started by configuring your DNS records.

Configure DNS Records

In order to set up the desired redirect, www.example.com to example.com or vice versa, you must have an A record for each name.

Open whatever you use to manage your DNS. For our example, we’ll use the DigitalOcean DNS.

If a domain (also known as a zone) record does not already exist, create one now. The hostname should be your domain, e.g. example.com, and the IP address should be set to the public IP address of your Apache server. This will automatically create an A record that points your domain to the IP address that you specified. If you are using another system to manage your domain, you may need to add this manually.

Next, add another A record with “www” as the hostname (or “www.example.com” if the partial subdomain doesn’t work), and specify the same IP address.

When you have created both records, it should look something like this:

Required A records

Note: This will also work with CNAME records, as long as the canonical name’s A record refers to the IP address of your Apache web server.

Now your server should be accessible via the www and non-www domain, but we still need to set up the redirect. We’ll do that now.

Enable Rewrite Module

In order to perform the 301 redirect, we will use the Apache mod_rewrite, or Rewrite, module. Doing so will ensure that your users can access your site with or without the www. prefix, and be redirected to the domain that you prefer.

First, enable the mod_rewrite module with this command:

  1. sudo a2enmod rewrite

With the Rewrite module enabled, we can configure Apache with redirect rules using .htaccess files.

Enable .htaccess Files

Open your Apache configuration file for editing. On Ubuntu, the default configuration file is located at /etc/apache2/sites-enabled/000-default.conf, so we will use that in our example:

  1. sudo vi /etc/apache2/sites-enabled/000-default.conf

Find the DocumentRoot of your site, and take a note of it. By default, it’s /var/www/html, so we will use that in our example configuration.

Add the following Directory directive to the configuration and be sure to substitute the DocumentRoot for the highlighted part:

Add to Apache configuration
 <Directory /var/www/html>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order allow,deny
    allow from all
 </Directory>

Save and exit.

Now restart Apache to put the change into effect:

  1. sudo service apache2 restart

Now Apache is configured to read .htaccess files located anywhere under the /var/www/html directory. Let’s add our Rewrite rules now.

Configure Rewrite Module

As we mentioned earlier, we will configure the Rewrite module using an .htaccess file.

Change directories to your DocumentRoot, in our case, /var/www/html:

  1. cd /var/www/html

Now open .htaccess for editing:

  1. sudo vi .htaccess

Of course, if you haven’t created the file before, it will be blank. Depending on which direction you want to redirect, use one of the following options.

Option 1: Redirect www to non-www

If you want redirect users from www to a plain, non-www domain, insert this configuration:

.htaccess — www to non-www
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

Save and exit. The changes should go into effect immediately. Note that if you are using HTTPS, you should update “http”, in the RewriteRule line, to “https”.

Use this curl command to ensure that the non-www domain redirects to the www domain (replace the highlighted part with your actual domain):

curl -I http://www.example.com

You should get a 301 Moved Permanently response, that shows the non-www redirect location, like this:

Output:
HTTP/1.1 301 Moved Permanently Date: Fri, 01 May 2015 21:18:33 GMT Server: Apache/2.4.7 (Ubuntu) Location: http://example.com/ Content-Type: text/html; charset=iso-8859-1

Of course, you should access your domain in a web browser (www and non-www) to be sure.

Option 2: Redirect non-www to www

If you want redirect users from a plain, non-www domain to a www domain, insert this configuration:

.htaccess — non-www to www
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Save and exit. the changes should go into effect immediately. Note that if you are using HTTPS, you should update “http”, in the RewriteRule line, to “https”.

Use this curl command to ensure that the non-www domain redirects to the www domain (replace the highlighted part with your actual domain):

curl -I http://example.com

You should get a 301 Moved Permanently response, that shows the www redirect location, like this:

Output:
HTTP/1.1 301 Moved Permanently Date: Fri, 01 May 2015 21:18:33 GMT Server: Apache/2.4.7 (Ubuntu) Location: http://www.example.com/ Content-Type: text/html; charset=iso-8859-1

Of course, you should access your domain in a web browser (www and non-www) to be sure.

Conclusion

That’s it! Your Apache redirect is now configured properly, and your users will be able to access your web server via your non-www and www domain.

If you would like to understand more about mod_rewrite, the Apache feature that we used to implement the redirect, feel free to read this tutorial: How To Set Up Mod_Rewrite.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
10 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Why would you use htaccess and the rewrite module and not something like this?

<VirtualHost *:80>
    ServerName www.example.com
    Redirect permanent / http://example.com/
</VirtualHost>

<VirtualHost *:80>
    ServerName example.com
    DocumentRoot /var/www/html
</VirtualHost>

I’m getting this output on the curl -I command

HTTP/1.1 200 OK Date: Tue, 05 Dec 2023 19:47:01 GMT Server: Apache/2.4.57 (Ubuntu) Content-Length: 56657 X-Frame-Options: DENY Vary: Cookie,Accept-Encoding X-Content-Type-Options: nosniff Referrer-Policy: same-origin Cross-Origin-Opener-Policy: same-origin Content-Type: text/html; charset=utf-8

Hi I followed the steps in this tutorial, but if I go to www.example.com, now it redirects me to example.com/example.wsgi/ instead of example.com. Do you know how I can fix this?

For me this is resulting in double // when there was a path:

http://%1/$1

meaning that the redirects were looking like:

Location: http://mydomain.com//?hello=world

but this was 👍:

http://%1$1

Thanks, it saved my day.

Nice article but the title is what will mislead,the title says ‘redirecting www to non-www’ but it’s included also ‘redirecting non-www to www’. Many people might have passed this page on search because they could only see 'redirecting from www to non www.

Thanks you very much.

Tks. Works fine!

I get an ERR_TOO_MANY_REDIRECTS when I follow your guide. Can you give a little help to resolve this problem

Absolutely use the comment from SerMDQ …shortest, effective method.

Why can’t you just use ServerAlias on the site’s conf file? <VirtualHost *:80> ServerName example.com ServerAlias www.example.com DocumentRoot /web-dir <Directory … etc etc.etc </Directory>

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.