Ugacomp

How to Redirect www to the non-www Domain in Apache?

Where necessary, you may need to have access to a VPS server so you can follow how to implement the steps in this article.  You can get a cheaper VPS Server from Contabo with 4vCPU cores, 8GM RAM, and 32TB Bandwidth for less than $5.50 per month. Get this deal here now

Table of Contents

Cloud VPS S

$5.50 Monthly
  • 4 vCPU Cores | 8GB RAM

CLOUD VPS M

$15.50 Monthly
  • 6 vCPU Cores | 16GB RAM

CLOUD VPS L

$17.50 Monthly
  • 8 vCPU Cores | 24GB RAM

Redirecting your website visitors from the www version to the non-www version or vice versa is a common requirement for website owners. In this article, we will focus on how to implement this redirection in the Apache web server.

What is the difference between a www and a non-www domain?

Before delving into the technicalities of the redirection process, it is essential to understand the difference between www and non-www domains. The www prefix is a relic from the early days of the Internet and was used to specify that a particular address was part of the World Wide Web. Today, it has become more of a convention than a necessity. The non-www version, on the other hand, is cleaner and often preferred for its simplicity.

Do you really need to redirect a www domain to a non-www version?

Both “www” and non-www versions of your website address are technically valid. But having both versions accessible creates a problem: search engines might see them as two separate websites. This can be bad news for two reasons:

  • Split Personality

Search engines want to see your website as a single, unified entity. Having duplicate content across two URLs can confuse them and hurt your search ranking. Think of it like having two different Facebook profiles for the same person; it wouldn’t make much sense, right?

  • Link Power Divided

Backlinks are like votes that boost your website’s authority in the eyes of search engines. If links are divided between two versions of your website, you lose valuable ranking power.

RECOMMENDED READING: How to use Cloudflare on Namecheap Domain Pointed to Contabo

Creating a redirection will automatically send visitors from one version of your website (either www or non-www) to the other. This ensures that all traffic and link power are directed to a single location.

While both options are technically viable, it’s generally recommended to create a non-www version of your domain because it makes the URLs shorter and it’s easier for users to type in the browser

Redirection in Apache Server using the Config file

Redirecting www to the non-www domain in Apache involves modifying the server’s configuration files. Here’s a step-by-step guide to help you achieve this:

Locate the Apache configuration file

You will need to locate the Apache configuration file and this can vary based on your server setup. The common paths include /etc/apache2/apache2.conf, /etc/httpd/httpd.conf, or within a directory like /etc/apache2/sites-available/

If you’re running a Debian-based Linux system like Ubuntu, you can simply use the following command on your terminal to open the default Apache configuration file;

sudo nano /etc/apache2/sites-available/000-default.conf

This file contains the default configuration for the Apache web server, including the document root directory, which is the directory where Apache will look for web pages to serve. You can edit this file to change the default configuration, such as to add additional virtual hosts or to change the document root directory.

It is also important to note that the Apache configuration file on your server could have a different name based on how you set it up. Make sure to use the real name you assigned to your config file during the Apache server setup.

RECOMMENDED READING: How to Point a Domain Name from Namecheap to Contabo VPS

Add the redirection directive in the Apache configuration file

Inside the configuration file, you’ll need to add the necessary directive to handle the redirection. Here is the redirection code syntax you need to add below the ServerName directive you’re targeting:

 Redirect permanent / http://yourdomain.com/

In the context of an Apache web server, Redirect permanent is a directive used to instruct the server to perform a permanent redirect for a specific URL. This means that when a user requests the old URL, the server will automatically send a response with a 301 (Moved Permanently) status code, directing the user’s browser to the new URL.

RECOMMENDED READING: How can I fix Cloudron domain redirection issues?

In this example, the old or original URL is defined by the ServerName directive as www.yourdomain.com but we’re redirecting it to the new URL using the redirect permanent directive with http://yourdomain.com/ as the new URL. See the code below:

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

In these lines, replace www.yourdomain.com with your actual www domain and http://yourdomain.com/ with your non-www domain. The Redirect permanent directive ensures a 301 permanent redirect, which is beneficial for search engine optimization.

Save the changes to the configuration file and exit the text editor. You will have to restart Apache to apply the changes. You can do this by typing:

   sudo service apache2 restart

Or

   sudo systemctl restart apache2

Redirecting Using the mod_rewrite module

Another way of creating redirections in Apache is to use the mod-rewrite module. This tool is used to manipulate URLs in a variety of ways. It is a popular module used by web developers to create clean, user-friendly URLs, redirect users to different pages, and perform other tasks such as caching and load balancing.

RECOMMENDED READING: How to Install WordPress on a VPS Server using Cloudron?

Enable the mod_rewrite module

If the mod_rewrite module is not enabled, then you can activate it using the following command:

sudo a2enmod rewrite

Once you have enabled the mod_rewrite module, you need to restart the Apache service for the changes to take effect. To do this, run the following command:

sudo service apache2 restart

Add the redirect code to your .htaccess file

The redirect code needs to be added to the .htaccess file for your website. The .htaccess file is a configuration file that is used to modify the behavior of the Apache web server.

To edit the .htaccess file, open it in a text editor such as nano or vim. If the .htaccess file does not exist, you can create it by typing the following command:

touch .htaccess

Add the following code to the .htaccess file:

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

Here’s a breakdown of each line:

  • RewriteEngine On:

This line enables the mod_rewrite module.

  • RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]

This line sets a condition based on the “Host” header of the HTTP request. It checks if the hostname is exactly “www.example.com” and ignores the case using the [NC] flag.

  • RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]

This is a rewrite rule. It applies only if the preceding condition is met. It captures the part of the requested URL after the domain (using ^(.*)$), and then redirects the request to “https://example.com/” followed by the captured part. The [L] flag indicates that this is the last rule to be applied, and the [R=301] flag specifies a 301 HTTP status code for a permanent redirect.

Please remember to replace example.com with your own domain name.

Once you have added the redirect code to the .htaccess file, save and close it.

Redirection and SSL setup considerations

If you have an SSL certificate installed on www.example.com and you want to redirect users to example.com (without the www prefix), you generally do not need a separate SSL certificate for example.com. However, there are some important considerations to keep in mind:

Wildcard Certificate

A wildcard certificate is a type of SSL/TLS certificate that is designed to secure a domain and all its subdomains with a single certificate. The wildcard character (*) is used as a placeholder in the domain name to represent any subdomain.

For example, if you have a wildcard certificate for *.example.com, it would be valid for:

  • www.example.com
  • blog.example.com
  • api.example.com
  • and so on…

The asterisk (*) in the wildcard position allows the certificate to match any subdomain level. However, it only covers one level of subdomains. In the example above, the wildcard certificate for *.example.com would not cover sub.blog.example.com because it’s more than one level deep.

Wildcard certificates are convenient for organizations that have a large number of subdomains and want to secure them all with a single certificate, simplifying certificate management. Instead of obtaining and managing individual certificates for each subdomain, a wildcard certificate can be used to cover them all.

Therefore, if your SSL certificate for www.example.com is a wildcard certificate (e.g., *.example.com), it will cover all subdomains, including example.com. In this case, you won’t need a separate certificate for example.com.

Subject Alternative Name (SAN) Certificate

If your SSL certificate for www.example.com includes example.com as one of the Subject Alternative Names, it will also cover the non-www version. Again, no separate certificate is needed in this scenario.

In the context of SSL/TLS certificates, the Subject Alternative Name field allows a certificate to be valid for multiple domain names, IP addresses, or other identifiers. This is particularly useful in scenarios where a single certificate needs to be used for multiple variations of a domain, such as with or without the www prefix.

For example, suppose you have a domain example.com, and you want your SSL/TLS certificate to cover both www.example.com and blog.example.com. Instead of getting separate certificates for each subdomain, you can include both names in the SAN field of a single certificate.

Here’s a simplified example of what the SAN field might look like:

Subject Alternative Name:
    DNS:www.example.com
    DNS:blog.example.com

It’s important to note that while wildcard certificates are focused on securing a primary domain and its subdomains, SAN certificates offer the ability to secure multiple distinct domain names within a single certificate. This flexibility enables the certificate to secure multiple domains that may not share a common base domain. For instance, a SAN certificate could cover:

  • www.example.com
  • www.example.net
  • www.example.org
  • and so on…

Redirect Configuration

You need to ensure that your Apache server is correctly configured to handle the redirection. The Apache virtual host configuration for www.example.com should include a directive to redirect to https://example.com. Here’s an example:

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

    SSLEngine on
    SSLCertificateFile /path/to/www.example.com.crt
    SSLCertificateKeyFile /path/to/www.example.com.key
    SSLCertificateChainFile /path/to/www.example.com.ca-bundle

    <IfModule mod_rewrite.c>
        RewriteEngine on
        RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
        RewriteRule ^(.*)$ https://example.com$1 [L,R=301]
    </IfModule>
</VirtualHost>

Also, ensure that the SSL certificate paths and filenames are correct in your configuration.

Test the redirection

To ensure that the redirection is working correctly, open your web browser and type www.yourdomain.com. You should be automatically redirected to yourdomain.com. Additionally, you can use online tools like redirect-checker.org to confirm that the redirection is functioning as intended.

Why is the redirection not working?

If the redirect is not working, there are a few things you can check:

  • Make sure that the mod_rewrite module is enabled.
  • Make sure that the .htaccess file is located in the root directory of your website.
  • Make sure that the .htaccess file is readable by the Apache web server.
  • Make sure that the redirect code is correct.

Conclusion

Redirecting www to the non-www domain in Apache is a straightforward process that involves editing the server’s configuration files. By following the steps outlined in this guide, you can ensure that your website visitors are always directed to the preferred version of your domain. Consistency in your domain structure not only improves user experience but also plays a role in search engine optimization, making it a vital task for website owners to implement.

More Apache-related articles to explore

Hire us to handle what you want

Hire us through our Fiverr Profile and leave all the complicated & technical stuff to us. Here are some of the things we can do for you:

  • Website migration, troubleshooting, and maintenance.
  • Server & application deployment, scaling, troubleshooting, and maintenance
  • Deployment of Kubernetes, Docker, Cloudron, Ant Media, Apache, Nginx,  OpenVPN, cPanel, WHMCS, WordPress, and more
  • Everything you need on AWS, IBM Cloud, GCP, Azure, Oracle Cloud, Alibaba Cloud, Linode, Contabo, DigitalOcean, Ionos, Vultr, GoDaddy, HostGator, Namecheap, DreamHost, and more.
 

We will design, configure, deploy, or troubleshoot anything you want. Starting from $10, we will get your job done in the shortest time possible. Your payment is safe with Fiverr as we will only be paid once your project is completed.