Configure redirects in Apache


Published on 04 May 2023


Configure redirects in Apache

Intro: Configure redirects in Apache

Apache is one of the most popular web servers in use today, powering millions of websites around the world. One of the key features of Apache is its ability to configure redirects, which can be useful for managing website traffic and improving user experience.
In this instructional article, we will explore the basics of configuring redirects in Apache, including the different types of redirects, how to write redirect rules using mod_rewrite, and some common scenarios for implementing redirects.

What are Web Redirects

Redirects are a way of forwarding website visitors from one URL to another. This can be useful for a variety of reasons, such as when a page has been moved or renamed, or when you want to redirect traffic from one domain to another.

There are several types of redirects, including 301 (permanent), 302 (temporary), and others.

Each type of redirect serves a different purpose, and it's important to choose the right one for your situation.

Redirects have a significant impact on SEO and user experience

Redirects are an essential part of website management, and can have a significant impact on SEO and user experience.

For example, if you move a page without setting up a redirect, visitors who have bookmarked the old URL will be unable to find the new page. This can lead to frustration and a loss of traffic.

By setting up a redirect, you can ensure that visitors are automatically forwarded to the new page, preserving your traffic and improving user experience.

Installing Apache on Ubuntu

To install Apache in Ubuntu we have to open the terminal directly from the graphical environment or with the CTRL+AL+T key combination.
Inside the terminal we write the following:

sudo apt update
sudo apt install apache2

Configure redirects in Apache

To configure redirects in Apache, you will need to access the Apache configuration file.
This file is typically located:

  • On Linux Debian systems in the /etc/apache2/apache2.conf file.
  • On Windows systems in the C:\Program Files (x86)\Apache Group\Apache2\conf directory.
  • In case you cannot access the main Apache configuration file, you can also use the ".htaccess" configuration file. This file should be located in the main folder of your website, next to the index files that load the main page. But first you must have configured the server to recognize this type of htaccess files.
    If you have a shared cPanel server and you do not have access to the general server configuration, generally the htaccess file will be activated by default, and you will only have to create the file in a text editor and upload it to the root of the web to take effect the redirections and other options you want to perform.

    How to enable .htaccess in Apache configuration on Linux

    1. Use a text editor to open your configuration file:

       sudo nano /etc/apache2/sites-available/yoursite.com.conf
      
    2. After the VirtualHost block add the Directory directive as shown below:

      <VirtualHost *:80>
      ...
      </VirtualHost>
      <Directory /var/www/html/yoursite.com/public_html>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
      </Directory>
    3. Save the file, then restart apache:
      sudo service apache2 restart
    4. Now we can create the htaccess file in the root of the web and add the configuration we want as well as the necessary redirects:
      sudo nano /var/www/yourwebsite/.htaccess

Once you have located the configuration file, you can add redirect rules using the mod_rewrite module.

Apache Module mod_rewrite

Mod_rewrite is a powerful tool that allows you to write complex redirect rules using regular expressions.

The mod_rewrite module uses a rule-based rewrite engine, parsing regular expressions to rewrite URLs on the fly. 
The mod_rewrite module uses an unlimited number of rules where each rule can have an unlimited number of conditions that will allow a URL to be rewritten based on server variables, environment variables, HTTP headers or timestamps.

For example, you could use mod_rewrite to redirect all URLs containing the string "old-page" to a new page: 

RewriteRule ^old-page(.*)$
https://www.example.com/new-page$1 [R=301,L]

Once you have written your redirect rules, you should test them to ensure they are working correctly. You can do this by using a tool like curl to request the old URL and checking that you are redirected to the new URL.

Regular Expressions in Apache

A regular expression or RegEx is a generic text string used as a pattern to match long text strings that use the same pattern.

In Apache the most used regular expressions are the following, based on the regular expressions of the Perl programming language:

  • .
    Matches any single character
    Example: c.t will match cat, cot, cut, etc.
  • +
    Repeats the character before the + one or more times.
    Example: c+ is the same as c, cc, ccc, etc.
  • *
    Repeats the previous character zero or more times.
    Example: c* matches the same way as c+ but will also match an empty string.
  • ?
    Makes the character optional.
    Example: colou?r makes the character r optional and will match colory color.
  • \
    Escape from the next character
    Example: \a will match a
  • ^
    ^ followed by a character matches the beginning of the string with that character.
    Example: ^a matches a string starting with a
  • $
    $ preceded by a character matches the end of the string preceded by that character.
    Example: a$ matches a string ending with a.
  • ( )
    Group several characters into a single unit to use as a reference pattern.
    Example: (ab)+ matches ababab where + is applied to the group within parentheses.
  • [ ]
    Group of characters between square brackets of which are the choice of a single character among them.
    Example: c[uoa]t will choose a character among the characters "uoa", giving possible results "cut, coto cat".
  • [^ ]
    The character inside the bracket is deleted.
    Example: c[^a]t would be the same as cut but would not be worth cat.

Main directives for the operation of the mod_rewrite module

The mod_rewrite directives can be added in the main Apache configuration file "/etc/apache2/apache2.conf", inside the preferred VirtualHost block according to the port that is specified in the block.
They can also be added in the .htaccess file directly.
The main directives of the mod_rewrite module are the following:

  • The RewriteEngine directive will be used to enable or disable the rewriting at runtime of any given change in the set of web pages hosted on the server or for a particular web page in the case of using .htaccess.
    This directive sits at the top of the mod_rewrite module and allows the initiation of redirection and other directives.
    Syntax: RewriteEngine On | Off
    Example: RewriteEngine On
  • The RewriteBase directive specifies the URL prefix to use for per-directory RewriteRule directives, in .htaccess, and is required when you use a relative path in reference to the directory.
    Syntax: RewriteBase "/myfolder/"
  • AliasMatch maps URLs to file locations using regular expressions.
    Syntax: AliasMatch regex file-path|directory-path
    Example:
    AliasMatch "^/image/(.*)\.jpg$" "/folder/images/$1.jpg"
    Maps all files with jpg extension to the image folder with the same original name.
  • Alias maps URLs to file locations.
    Example:
    If we want http://yourweb.com/imgs/image/file.gif to be reflected in another folder without it originally being there, in the /image/file.gif folder.
    Alias "/image" "/imgs/image"
  • RewriteCond Directive

  • The RewriteRule directive will allow us to execute rewrite rules.
    It can be used more than once and its application order is important since one rule can affect another if they are located in different positions.
    For RewriteRule to work we must enable "RewriteEngine On" and the "FollowSymLinks" option for the directory where we are going to locate the web domain.

Example:

DocumentRoot "/var/www/yourweb.com"
AliasMatch "^/myfolder" "/folder/folder_1/sub_folder/myfolder"
<Directory "/folder/folder_1/sub_folder/myfolder">
    RewriteEngine On
    RewriteBase "/myfolder/"
    RewriteRule "^(.*)" "post.php?t=$1"
</Directory>

Basic Redirects in Apache

There are several common scenarios where you might want to configure redirects in Apache.

  • Redirecting HTTP traffic to HTTPS. This is important for security reasons, as HTTPS encrypts traffic between the server and the client, preventing eavesdropping and other attacks. To redirect HTTP traffic to HTTPS, you can add the following rule to your Apache configuration file:
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] 
  • Redirecting non-www URLs to www URLs. 
    This can help to ensure that all traffic is directed to a single domain, improving SEO and user experience.
    To redirect non-www URLs to www URLs, you can use the following rule:
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

  •  


Tips on SEO and Online Business

Next Articles

Previous Articles



All-in-one SEO software to increase the overall search engine ranking of your website