Guide to Apache Redirects

Leave your reply

Learn how to understand and configure Apache redirects on CentOS 7 and Ubuntu 14.04. Apache redirects are useful for a wide variety of situations, including redirecting visitors from the HTTP to HTTPS version of your site, redirecting traffic from a WWW to a non-WWW URL, and changing web page or directory names.

Requirements

  • Linux server running CentOS 7 or Ubuntu 14.04
  • Apache installed and running

301 Permanent vs 302 Temporary Redirect

The main difference between a 301 Permanent versus a 302 Temporary redirect has to do with a website's SEO. A 301 Permanent redirect is far more desirable from an SEO perspective.

Search engine crawlers treat a 302 redirect as temporary

When a search engine crawler hits a 302 redirect, it notes the new address and moves on. Depending on the crawler, it may flag the URL for a revisit at some point in the future.

The crawler does this because a 302 redirect is meant to indicate that the redirect is only temporary, and the "real" URL will be back online soon.

A 301 redirect preserves your SEO ranking

By comparison, when a search engine crawler encounters a 301 redirect, the crawler understands that this is a permanent redirect. It therefore not only notes the new URL, it also kicks off the process of transferring any page rank value from the old URL to the new one.

This transfer process is crucial for SEO purposes. It allows you to change a site's URLs without losing any of the valuable SEO "juice" that the pages have earned.

Always force a 301 redirect

Thus, whenever creating a redirect, you always want to specify that it is a 301 redirect. In many situations, if the redirect type is not specified, it will default to a 302 redirect.

Basic 301 Redirects

If you only need to redirect one (or a small number of) URLs, it is an easy matter to add these to the site's Apache configuration file individually.

Basic URL Redirect

A 301 redirect uses the Redirect directive in an Apache configuration file with the syntax:

Redirect 301 [old URL] [new URL]

For example, let's say the owners of example.com have decided to move their site's blog from a subdirectory (http://example.com/blog) to its own canonical domain (http://blog.example.com). The Redirect directive would read:

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

The new URL can also be an external URL, like this example which redirects traffic from http://example.com/store to an Amazon store page:

Redirect 301 /store https://www.amazon.com/s?marketplaceID=AT32311PKK0DER&me=ASEVS99O66653FS73&merchant=ASEV33F6FS73&redirect=true

This allows the site's owner to say "Visit example.com/store to shop my Amazon store" instead of having to pass along a long, complicated URL.

The Redirect directive needs to go inside the VirtualHost command block in the site's main Apache configuration file.

By common convention, this Apache configuration file is usually:

  • CentOS 7/etc/httpd/conf.d/example.com.conf
  • Ubuntu 14.04/etc/apache2/sites-available/example.com.conf

Note: The location and filename of a site's Apache configuration file can vary based on how you or your server administrator has set up hosting.

Edit this file with your editor of choice, for example with the command:

  • CentOS 7sudo nano /etc/httpd/conf.d/example.com.conf
  • Ubuntu 14.04sudo nano /etc/apache2/sites-available/example.com.conf

Scroll through the file until you find the VirtualHost command block, which will look something like:

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

Add the Redirect to the VirtualHost command block, but be sure to put it outside any Directory command blocks. For example:

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

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

  • CentOS 7sudo systemctl restart httpd
  • Ubuntu 14.04sudo service apache2 restart

Redirect WWW to a Non-WWW Website URL

It is common practice to alias the WWW version of a URL to the non-WWW version (or vice versa) using a ServerAlias line in the site's Apache configuration file. Although this functions well enough for website visitors, it is not considered "best practices" from an SEO standpoint.

Using ServerAlias instead of a 301 redirect risks the website being flagged as "duplicate content." Some search engine crawlers do not realize that www.example.com and http://example.com are the same URL.

There is no difference from an SEO standpoint between the WWW and non-WWW versions of your URL. The important thing is that you choose one and use it consistently.

Note: The following directions will redirect traffic from the WWW to the non-WWW version of your URL. If you prefer the opposite (redirecting traffic from the non-WWW version to the WWW version), simply edit the commands as needed.

This Redirect directive needs to go inside a new VirtualHost command block in the site's main Apache configuration file.

By common convention, this Apache configuration file is usually:

  • CentOS 7/etc/httpd/conf.d/example.com.conf
  • Ubuntu 14.04/etc/apache2/sites-available/example.com.conf

Note: The location and filename of a site's Apache configuration file can vary based on how you or your server administrator has set up hosting.

Edit this file with your editor of choice, for example with the command:

  • CentOS 7sudo nano /etc/httpd/conf.d/example.com.conf
  • Ubuntu 14.04sudo nano /etc/apache2/sites-available/example.com.conf

Scroll through the main VirtualHost command block, which will probably look something like this:

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

If you see a line in this command block which reads:

ServerAlias www.example.com

Delete this line.

Scroll to the bottom of the file and add a new VirtualHost command block at the bottom:

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

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

  • CentOS 7sudo systemctl restart httpd
  • Ubuntu 14.04sudo service apache2 restart

Set up mod_rewrite and Allow .htaccess Files

For more complicated 301 redirects, the Apache module mod_rewrite is the best choice. This module is fast, flexible, and powerful.

Enable mod_rewrite on CentOS 7

mod_rewrite is enabled by default on CentOS 7. If you find that it has not been enabled, you can enable it by editing the base module configuration file with the command:

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

Add the following line, or uncomment it if it has been commented out:

LoadModule rewrite_module modules/mod_rewrite.so

Next, enable the use of .htaccess files. To do this, edit the site's main Apache configuration file.

By common convention, this Apache configuration file is usually /etc/httpd/conf.d/example.com.conf on CentOS 7.

Note: The location and filename of a site's Apache configuration file can vary based on how you or your server administrator has set up hosting.

Edit this file with your editor of choice, for example with the command:

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

Scroll through the main VirtualHost command block, which will probably look something like this:

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

In the Directory block, change AllowOverride from the default None to All:

AllowOverride All

If there is no Directory block in the VirtualHost command block, add one which reads:

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

Be sure to use the correct path to your website's document root.

Save and exit the file. Restart Apache so that the changes take effect:

sudo systemctl restart httpd

Enable mod_rewrite on Ubuntu 14.04

To enable mod_rewrite use the command:

sudo a2enmod rewrite

This will enable the module if it has not already been enabled. Restart Apache for the changes to take effect:

sudo service apache2 restart

Next, allow the use of .htaccess files. To do this, edit the site's main Apache configuration file.

By common convention, this Apache configuration file is usually /etc/apache2/sites-available/example.com.conf on Ubuntu 14.04.

Note: The location and filename of a site's Apache configuration file can vary based on how you or your server administrator has set up hosting.

Edit this file with your editor of choice, for example with the command:

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

Scroll through the main VirtualHost command block until you find the Directory command block, which will probably look something like this:

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

Change AllowOverride from the default None to All:

AllowOverride All

If there is no Directory block in the VirtualHost command block, add one which reads:

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

Be sure to use the correct path to your website's document root.

Save and exit the file. Restart Apache so that the changes take effect:

sudo service apache2 restart

Create a .htaccess File

Now that you have configured your site to use mod_rewrite and allow .htaccess files it's time to move to the document root (main web directory) for your website and create a .htaccess file.

This filename must be created exactly as shown, with a period at the beginning of the name. You do not need to restart Apache after making changes to a .htaccess file.

First, switch to your site's document root, for example:

cd /var/www/example.com/html

Next, create the .htaccess file here with the command:

sudo nano .htaccess

This file is where all of your mod_rewrite configurations will be set. Let's start with a simple test to make sure everything is working correctly.

Add the following lines to this file:

RewriteEngine on
RewriteRule ^hello.html$ goodbye.html 

This rule will redirect requests for hello.html to the page goodbye.html.

Save and exit the file.

Next, create the two files with the commands:

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

Now visit the hello.html file in a browser. You should be redirected to goodbye.html which says "Goodbye."

Point Multiple Domains to the Same Website

There are several reasons why you may want to point multiple URLs to the same website.

  • If your main website is example.com, you may want to buy example.net and example.org as well in order to capture the namespace.
  • It is a good practice to lock in common misspellings of your domain name like exampl.com or exmple.com.
  • You may also want to own variations of your domain name, like the-example.com or my-example.com.

Although you can simply point these domain names to your main website, it is wise to set up 301 redirects to do the job. This is what Google recommends among others

To set up a 301 redirect to point multiple domain names to the same website, first set up mod_rewrite and .htaccess files , then add the following lines to the site's .htaccess file:

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

This redirects traffic from example.net to example.com.

These rules will need to be customized to fit your domain names and desired results. For example, to redirect traffic to the WWW version of the URL (www.example.com) instead, you would use:

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

Redirect Visitors to the SSL-Secured Version of Your Site

If you want to be sure that all traffic on your site is secured via SSL, you will want to redirect all requests for http://example.com URLs to https://example.com instead.

To set up a 301 redirect to send visitors to the HTTPS version of a website, first set up mod_rewrite and .htaccess files , then add the following lines to the site's .htaccess file:

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

If you prefer to redirect traffic to the WWW version of your domain name, use the following rules instead:

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

Renaming Web Pages and Moving Directories

There are some situations where you have to rename an existing web page or directory. This will break any links which point to that page, which not only ruins the visitor's experience, it also cuts into your SEO.

After you set up mod_rewrite and .htaccess files , use the following rules in the site's .htaccess file.

To rename a web page

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

To rename a directory

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

In the above examples, the names of the files and directories are given as a path relative to the website's document root. There are three options for paths:

  • A full filesystem path (/var/www/html/new-page.html)
  • A web path relative to the document root (/new-page.html)
  • An absolute URL (http://example.com/new-page.html)

More Details About mod_rewrite

mod_rewrite uses regular expressions to match and substitute URLs. To enable mod_rewrite, the first line of the rules in the .htaccess file must always be:

RewriteEngine on

The heart of mod_rewrite is RewriteRules, often in conjunction with a RewriteCond.

RewriteRule

A RewriteRule has three parts:

RewriteRule [pattern] [substitution] [flags]

The pattern is built using regular expressions. If you are familiar with regular expressions, this mod_rewrite cheat sheet is a helpful tool.

The substitution can be:

  • A full filesystem path (/var/www/html/blog/index.php)
  • A web path relative to the document root (/blog)
  • An absolute URL (http://example.com/blog/index.php)

The flag is optional. Some of the most common include:

  • L: Indicating that this is the last in a series of rules.
  • R=301: Forcing a 301 redirect.
  • NC: Ignores capitalization so that the rule is not case-sensitive.

A full list of the available flags can be found on the official Apache website.

Sometimes a RewriteRule is prefaced by a RewriteCond. This specifies the conditions under which the RewriteRule will be used.

RewriteCond

A RewriteCond also has three parts:

RewriteCond [test string] [condition] [flags]

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

The condition can be one of three things:

  • A regular expression
  • A string comparison
  • A file/path test

The flag is optional. Three flags are available for the RewriteCond:

  • NC: Ignores capitalization so that the condition is not case-sensitive.
  • OR: Logical "or."
  • NV: "No Vary," the header name will not be added to the Vary response header.

RewriteRule Versus Redirect

Many people wonder what the difference is between RewriteRule and Redirect. Both can be used in a .htaccess file to redirect website traffic.

The main difference is that RewriteRule is handled by mod_rewrite, whereas Redirect is handled by mod_alias.

mod_rewrite

  • Uses RewriteRule and RewriteCond.
  • Much more powerful, since it uses regular expressions to match and replace URLs.
  • Can be more difficult to use.
  • Might not be installed or enabled by default.

mod_alias

  • Uses Redirect and RedirectMatch.
  • Not as configurable.
  • Can be easier to use.
  • Is already enabled by default in most Apache installations.

Whether you use mod_rewrite or mod_alias rules, you will always want to specify a 301 Permanent redirect.