Apache redirects: Instructions for CentOS and Ubuntu

Apache redirects are useful for a wide variety of situations. 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 understand and configure Apache redirects on CentOS and Ubuntu.

Dedicated Server from IONOS

Hardware meets cloud: dedicated server with cloud integration and per-minute billing, including a personal assistant! 

24/7 support
Unlimited traffic
SSL certificate

301 or 302 redirect: What’s the difference?

When looking at redirects, it is important to distinguish 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 perspective. If a search engine crawler encounters such a redirect, it understands that it is a permanent redirect. For this reason, it not only notes the new URL, but also initiates the process of transferring 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 situations, 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 individually in your project’s Apache configuration file.

Simple URL redirect

For a single 301 redirect, use the redirect directive in the Apache configuration 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 communicated, for example, the catchy URL example.com/store instead of having to submit the long, complicated 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/store https://www.amazon.com/s?marketplaceID=..

    The Apache redirect directive must always be included in the VirtualHost command block in the main web server configuration 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 configuration file may vary - depending on how you or your server administrator 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 VirtualHost 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 VirtualHost 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 subdirectory on your current site in the same way. For example, suppose you want to move your site’s blog from a subdirectory ('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 “ServerAlias” line in the Apache configuration file. Although this approach works well from a visitor perspective, it is not considered “best practice” from an SEO perspective. This is because using “ServerAlias” instead of a 301 redirect carries the risk that content in question could be flagged as duplicate content. Generally speaking, however, there is no difference 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 configuration 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 individual domain):

    ServerAlias www.example.com

    Delete this line and scroll to the end of the file. Add the following new “VirtualHost” 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 manipulate URLs in a simple way. You can define the appropriate 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 configuration 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 configuration file.

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

    Scroll down to the main VirtualHost 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 “AllowOverride” from “None” to “All”:

    AllowOverride All

    If the directory entry is missing in the VirtualHost 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 configuration file:

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

    Scroll down to the main VirtualHost 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 “AllowOverride” line, replace the default entry “None” with “All”:

    AllowOverride All

    If the directory entry is missing in the VirtualHost 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 configuring 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 individual mod_rewrite configurations. 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 redirected 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 purchasing example.net and example.org.
    • It makes sense to register typical misspellings 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 typosquatting.
    • 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 redirected from example.net to example.com. Now simply customize 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 elementary importance that all traffic on your website is secured via SSL/TLS. Also for this case, you can work with an Apache 301 redirect that automatically 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 configuration file:

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

    Renaming web pages and moving directories

    There are situations 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 experience, 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 directories 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 information about mod_rewrite

    The mod_rewrite module uses regular expressions 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 RewriteRules. Each RewriteRule consists of three parts:

    RewriteRule [pattern] [substitution] [flags]

    The pattern is created using regular expressions. The following substitutions 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 sensitivity so the rule is not case sensitive

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

    In some cases, a RewriteRule is introduced by a RewriteCond. This specifies the conditions under which the RewriteRule takes effect.A RewriteCond 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 conditions:

    • regular expressions
    • string comparisons
    • file/path tests

    Flags are again optional in this case. Three flags are available for RewriteCond:

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

    What is the difference between RewriteRule and redirect?

    Both RewriteRule and Apache 301 Redirect can be distinguished in an .htaccess file to redirect website traffic.

    The main difference is that a RewriteRule is implemented by the mod_rewrite module and a redirect is implemented by the mod_alias module.

    mod_rewrite mod_alias
    uses RewriteRule and RewriteCond uses Redirect and RedirectMatch
    very versatile as it uses regular expressions to match and replace URLs not very configurable
    can be difficult to use easy to use
    may not be installed or enabled by default enabled by default in most Apache installations

    Wait! We’ve got something for you!
    Have a look at our great prices for different domain extensions.


    Enter the web address of your choice in the search bar to check its availability.
    .org
    $1/1st year
    then $20/year
    .com
    $1/1st year
    then $15/year
    .info
    $1/1st year
    then $20/year
    .me
    $1/1st year
    then $20/year