How to use redirects in apache Webserver


TL;DR for how to use redirects in apache:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteRule ^index\.html http://bluegrid.io [R=301]
</IfModule>

This example will redirect a request for /index.html to http://bluegrid.io with status code 301 (Permanent redirect).

Specification:

OS Version: Ubuntu Os 18.04.3 (LTS) x64
Apache version: Apache/2.4.29 (Ubuntu)

Full read:

Redirects in the apache Webserver need module “rewrite.load” enabled. To enable it use the below command:

bluegrid-edu:~# ln -s /etc/apache2/mods-available/rewrite.load /etc/apache2/mods-enabled/rewrite.load

Redirects function in a way that web server sends a 30X status code back to the client with information about where to go for the requested content. This is common practice when we have changed the location of the existing pages or posts. So, when the browser requests one of these pages that have been moved we are telling it where to find it. As you can see there are multiple back and forth between client and server before the client gets what they need:

30X rewrite diagram
30X rewrite diagram

Now, to actually set up the redirection use the below code in the .htaccess file:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteRule ^index\.html http://bluegrid.io [R=301]
</IfModule>

The above example defined the condition for redirect via regular expression (regex), it matches the request for /index.html file and redirects this request to http://bluegrid.io. Of course, that is IF the rewrite module is enabled (which we did as the first step). Redirect is with status code 301 (Permanent redirect).

Let’s confirm the configuration works:

bluegrid-edu:~# curl -I http://bluegrid.io/index.html
HTTP/1.1 301 Moved Permanently
Date: Sun, 26 Jul 2020 19:57:48 GMT
Server: Apache/2.4.29 (Ubuntu)
Location: http://bluegrid.io
Content-Type: text/html; charset=iso-8859-1

That’s it!

Share this post

Share this link via

Or copy link