Setting up redirects using .htaccess files

Htaccess or Hypertext Access is a configuration file that is used to set per-directory settings on apache-based web servers.

While .htaccess can be used for a lot of different server configurations in this guide, we will go over how to use .htaccess files to configure redirects for your website and give you a few scenarios in which you might want to use it.

Installing Apache

First, we will install the apache web server

apt update && apt upgrade
apt-get install apache2

Then we will start the web server

systemctl enable apache2
systemctl start apache2

You can then enter the IP of the server into your browser and you will get a page similar to this:

Enabling .htaccess file

You will need to edit the apache configuration. To do so enter the following file:

nano /etc/apache2/apache2.conf

Locate the section that starts with <Directory> and contains the directory path for the directory you want to allow .htaccess files in.

For example, if you want to allow .htaccess to have an effect on files in the /var/www/html directory, you would look for a section that looks like this:

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

This will allow .htaccess to have control over all other subdirectories under /var/www/

The AllowOverride line specifies what directives .htaccess files can override in the main Apache configuration. Change this line to All to allow all directives in .htaccess files.

AllowOverride All

Save the configuration and restart Apache:

sudo systemctl restart apache2

Setting up redirects

In order for us to set up redirects correctly we will need to be aware of a few HTTP status codes first:

HTTP Status Codes

301-This code informs the client that the site they are looking for was been relocated permanently and redirects them to the new URL automatically

302- This code is used when the website is temporarily moved to a new URL

404 -This code informs the client that the webpage they are looking for doesn't exist. You can use htaccess to set up a custom 404 page.

Configuring the redirects

To set up a redirect create the .htaccess file in the /var/www directory:

Redirect a page to another page with the following config:

RewriteEngine On
Redirect 301 /old-web-page.html https://www.example-web-site.com/new-web-page.html

Redirect from one URL to another:

RewriteEngine On
RewriteRule ^old-domain.com$ /new-domain.com [R=301,L]

Redirect the whole website

RewriteEngine On
Redirect 301 https://www.old-example-web-site.com https://www.example-web-site.com

You can set up a custom 404 page. If the client tries to access a page that is no longer up you can redirect them to your custom 404 page

RewriteEngine On
Redirect 404 https://www.example-web-site.com/old-page.html /404.html

Don't forget to specify the correct HTTP status code for the redirect you are performing.