Apache redirects are useful for a wide variety of situ­ations. Among other things, you can use handy redirects to direct visitors from the HTTP to the HTTPS (Apache http to https redirect) version of your website, redirect traffic from a www to a non-www URL, or even change website and directory names. We help you un­der­stand and configure Apache redirects on CentOS and Ubuntu.

Dedicated Server
Per­form­ance through in­nov­a­tion
  • En­ter­prise hardware
  • Con­fig­ur­able hardware equipment
  • ISO-certified data centres

301 or 302 redirect: What’s the dif­fer­ence?

When looking at redirects, it is important to dis­tin­guish between 301 and 302 redirects. The former status code (301) stands for a permanent redirect, while the latter (302) indicates a temporary redirect.

A 301 redirect is far more desirable from an SEO per­spect­ive. If a search engine crawler en­coun­ters such a redirect, it un­der­stands that it is a permanent redirect. For this reason, it not only notes the new URL, but also initiates the process of trans­fer­ring any Page Rank value from the old URL to the new one - the already achieved SEO ranking is thus preserved.

On the other hand, if a crawler detects a 302 redirect, it notes the new address and moves on. Depending on the crawler, it may mark the URL for a repeat visit sometime in the future. This happens because a 302 redirect is supposed to indicate that the redirect is only temporary and the ‘real’ URL will be back online soon.

Tip

Always specify that a redirect is a 301 redirect when creating it. In many situ­ations, redirects default to 302 if the redirect type is not specified.

Apache301 Redirects: Basics

If you only need to redirect a single URL or a small number of URLs, you can easily mark them up in­di­vidu­ally in your project’s Apache con­fig­ur­a­tion file.

Simple URL redirect

For a single 301 redirect, use the redirect directive in the Apache con­fig­ur­a­tion file. The syntax for this looks like this:

Redirect 301 [old URL] [new URL]

The new URL can also be an external URL. This way, users can be com­mu­nic­ated, for example, the catchy URL example.com/store instead of having to submit the long, com­plic­ated URL of an Amazon store page. The next example redirects traffic from example.com/store to an Amazon store page like this:

Redirect 301 example.com/shop https://www.amazon.com/s?marketplaceID=..

The Apache redirect directive must always be included in the Vir­tu­al­Host command block in the main web server con­fig­ur­a­tion file. By default, the file can be found in the following locations:

  • CentOS: /etc/httpd/conf.d/example.com.conf
  • Ubuntu: /etc/apache2/sites-available/example.com.conf
Note

The location and filename of the Apache con­fig­ur­a­tion file may vary - depending on how you or your server ad­min­is­trat­or set up the hosting.

Edit this file with an editor of your choice, such as the command line editor nano.

CentOS:

sudo nano /etc/httpd/conf.d/example.com.conf

Ubuntu:

sudo nano /etc/apache2/sites-available/example.com.conf

Scroll through the file until you find the Vir­tu­al­Host command block, which looks something like this:

<VirtualHost *:80>
ServerName example.com
    <Directory "/var/www/example.com/html">
    AllowOverride All
    </Directory>
</VirtualHost>

Now add the Apache redirect directive to the Vir­tu­al­Host command block. When doing so, make sure to place the directive outside of directory command blocks:

<VirtualHost *:80>
ServerName example.com
Redirect 301 /blog https://blog.example.com
    <Directory "/var/www/example.com/html">
    AllowOverride All
    </Directory>
</VirtualHost>

Save and close the file, then restart Apache for the changes to take effect:

CentOS:

sudo systemctl restart httpd

Ubuntu:

sudo service apache2 restart

Apache: Redirect a directory

You can also redirect a sub­dir­ect­ory on your current site in the same way. For example, suppose you want to move your site’s blog from a sub­dir­ect­ory ('http://example.com/blog') to its own canonical domain ('http://blog.example.com'). The Apache redirect policy would be:

Redirect 301 /blog https://blog.example.com

Redirect from www to non-www domains

It is common to redirect the www version of a URL to the non-www version (or vice versa) via a ‘Server­Ali­as’ line in the Apache con­fig­ur­a­tion file. Although this approach works well from a visitor per­spect­ive, it is not con­sidered ‘best practice’ from an SEO per­spect­ive. This is because using ‘Server­Ali­as’ instead of a 301 redirect carries the risk that content in question could be flagged as duplicate content. Generally speaking, however, there is no dif­fer­ence between the www and non-www versions of an URL from an SEO point of view. The important thing is that you pick one of them.

In the following, we redirect the traffic from the www to the non-www variant. Again, we need the main Apache con­fig­ur­a­tion file, which you again open with the editor of your choice - for example, the command line editor nano.

CentOS:

sudo nano /etc/httpd/conf.d/example.com.conf

Ubuntu:

sudo nano /etc/apache2/sites-available/example.com.conf

In the command block, look for the following line (with your project’s in­di­vidu­al domain):

ServerAlias www.example.com

Delete this line and scroll to the end of the file. Add the following new ‘Vir­tu­al­Host’ command block there:

<VirtualHost *:80>
    ServerName www.example.com
    Redirect 301 / https://example.com/
</VirtualHost>

Save and close the file. Then restart Apache for the changes to take effect.

Complex Apache redirects with mod_rewrite.

For more complex 301 redirects, the Apache module mod_rewrite is the best choice. This module is fast, flexible, and powerful - and gives you the ability to ma­nip­u­late URLs in a simple way. You can define the ap­pro­pri­ate rules in a .htaccess file.

Enable mod_rewrite on CentOS

mod_rewrite is enabled by default on CentOS. If you find that it has not been enabled, you can turn it on at any time in the module’s base con­fig­ur­a­tion file. To do this, first open the file with the nano editor:

sudo nano /etc/httpd/conf.modules.d/00-base.conf

Add the following line or enable it if it was commented out:

LoadModule rewrite_module modules/mod_rewrite.so

In the next step, enable the use of .htaccess files. To do this, open the main Apache con­fig­ur­a­tion file.

sudo nano /etc/httpd/conf.d/example.com.conf

Scroll down to the main Vir­tu­al­Host command block, which should look something like the following, as mentioned:

<VirtualHost *:80>
ServerName example.com
    <Directory "/var/www/example.com/html">
    AllowOverride None
    </Directory>
</VirtualHost>

Change the entry for ‘Al­lo­wOver­ride’ from ‘None’ to ‘All’:

AllowOverride All

If the directory entry is missing in the Vir­tu­al­Host command block, add it manually:

<Directory "/var/www/example.com/html">
    AllowOverride All
    </Directory>
Note

Make sure to use the correct path to the root directory of your website.

Save and exit the file. Restart Apache for the changes to take effect:

sudo systemctl restart httpd

Enable mod_rewrite on Ubuntu

To enable mod_rewrite on an Ubuntu server, use the following command:

sudo a2enmod rewrite

Restart Apache for the changes to take effect:

sudo service apache2 restart

Next, allow the use of .htaccess files. To do this, edit the main Apache con­fig­ur­a­tion file:

sudo nano /etc/apache2/sites-available/example.com.conf

Scroll down to the main Vir­tu­al­Host command block and find the directory command block (Directory), which should look something like this:

<Directory /var/www/example.com/html/>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

In the ‘Al­lo­wOver­ride’ line, replace the default entry ‘None’ with ‘All’:

AllowOverride All

If the directory entry is missing in the Vir­tu­al­Host command block, add it manually:

<Directory /var/www/example.com/html/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

Save and exit the file. Restart the web server for the changes to take effect:

sudo service apache2 restart

Create .htaccess file for Apache redirects

After con­fig­ur­ing Apache to use mod_rewrite and allow .htaccess files, it’s time to go to your website’s document directory (root directory) and create an .htaccess file.

Note

You do not need to restart Apache after making changes to an .htaccess file.

If you have not made any changes, go directly to the root directory of your Apache web server by typing the following:

cd /var/www/html

In the directory now create the .htaccess file and open it with the following command:

sudo nano .htaccess

Specify your in­di­vidu­al mod_rewrite con­fig­ur­a­tions. Start with a simple test to make sure everything is working properly by adding the following lines to this file:

RewriteEngine on
RewriteRule ^hello.html$ goodbye.html

This rule redirects requests for hello.html to the goodbye.html page. Save and exit the file, and then create the two HTML documents with the following commands:

sudo echo "Hello" >> hello.html
sudo echo "Goodbye" >> goodbye.html

Now access the hello.html page in a browser. You should be re­dir­ec­ted to goodbye.html via Apache redirect and see the message ‘Goodbye’.

Redirect multiple domains to the same URL via Apache redirect

There are several reasons why you should redirect different domains to the same address:

  • If your main site is example.com, you can best capture the namespace by pur­chas­ing example.net and example.org.
  • It makes sense to register typical mis­spellings of your domain name like exampl.com or exmple.com as well and include them in your strategy. This way you also protect yourself against so-called ty­po­squat­ting.
  • You may also simply own variants of your domain name such as the-example.com or my-example.com, which should also lead visitors to your web project when accessed.

Although you can redirect these domain names to your main page in the usual way, from the SEO point of view it is advisable to set up 301 redirects in order to achieve your set goals.

To redirect multiple domains to the same domain via Apache redirect, first enable the mod_rewrite module as described in the previous section and set up a suitable .htaccess file. Then add the following lines to the .htaccess file:

RewriteEngine on
RewriteCond %{HTTP_Host} ^(www\.)?example\.net$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301]

In the example, traffic is re­dir­ec­ted from example.net to example.com. Now simply customise this rule to your domain names and desired results. For example, to redirect traffic to the www version of the URL (www.example.com), you would use the following:

RewriteEngine on
RewriteCond %{HTTP_Host} ^(www\.)?example\.net$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301]

Apache: HTTP to HTTPS redirect: How it works

For the safety of your users and your search engine ranking it is of ele­ment­ary im­port­ance that all traffic on your website is secured via SSL/TLS. Also for this case, you can work with an Apache 301 redirect that auto­mat­ic­ally redirects visitors to the HTTPS version of your pages.

Again, first set up mod_rewrite and .htaccess file and then add the following lines to the con­fig­ur­a­tion file:

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule (.*) https://example.com$1 [R=301,L]

Renaming web pages and moving dir­ect­or­ies

There are situ­ations when you need to rename an existing page or directory. This will break all links pointing to that page - which not only degrades the user ex­per­i­ence, but also affects your SEO.

Use the following rules in the .htaccess file (after setting up mod_rewrite and .htaccess files).

Rename web page:

RewriteEngine on
RewriteRule ^old-page.html$ /new-page.html [R=301]

Rename directory:

RewriteEngine on
RewriteRule ^old-directory/ /new-directory/ [R=301]

In the examples above, the names of files and dir­ect­or­ies are specified as paths relative to the site’s root directory. There are three path options:

  • a full file system path such as /var/www/html/new-page.html
  • a web path relative to the root directory like /new-page.html
  • an absolute URL like 'http://example.com/new-page.html'

Summary of the most important in­form­a­tion about mod_rewrite

The mod_rewrite module uses regular ex­pres­sions to match and replace URLs. To enable mod_rewrite, the first line of the rules in the .htaccess file must always look like this:

RewriteEngine on

The heart of mod_rewrite are Re­writeR­ules. Each Re­writeR­ule consists of three parts:

RewriteRule [pattern] [substitution] [flags]

The pattern is created using regular ex­pres­sions. The following sub­sti­tu­tions can be made:

  • a full file system path
  • a web path relative to the root directory
  • an absolute URL

Flags are optional. Some of the most common flags are:

  • L: indicates that this is the last in a series of rules
  • R=301: forces a 301 redirect
  • NC: ignores case sens­it­iv­ity so the rule is not case sensitive

For a complete list of available flags, see the official Apache website.

In some cases, a Re­writeR­ule is in­tro­duced by a Re­write­Cond. This specifies the con­di­tions under which the Re­writeR­ule takes effect. A Re­write­Cond also consists of three parts:

RewriteCond [test string] [condition] [flags]

The test string is typically a server variable with the format %{VARIABLE NAME}.

There are three types of con­di­tions:

  • regular ex­pres­sions
  • string com­par­is­ons
  • file/path tests

Flags are again optional in this case. Three flags are available for Re­write­Cond:

  • NC: ignores case, so the condition is case-in­sens­it­ive
  • OR: logical “or”
  • NV (‘No Vary’): the header name will not be included in the Vary response header.

What is the dif­fer­ence between Re­writeR­ule and redirect?

Both Re­writeR­ule and Apache 301 Redirect can be dis­tin­guished in an .htaccess file to redirect website traffic.

The main dif­fer­ence is that a Re­writeR­ule is im­ple­men­ted by the mod_rewrite module and a redirect is im­ple­men­ted by the mod_alias module.

mod_rewrite mod_alias
uses Re­writeR­ule and Re­write­Cond uses Redirect and Re­dir­ect­Match
very versatile as it uses regular ex­pres­sions to match and replace URLs not very con­fig­ur­able
can be difficult to use easy to use
may not be installed or enabled by default enabled by default in most Apache in­stall­a­tions
Go to Main Menu