Apache URL redirection

The Big Picture

Do you agree on that “A picture is worth a thousand words“? If so, then you’ll find the following image is the best way for you to see the big picture of what an Apache URL redirections does, all the involved files are exposed in there.

Apache URL redirection – the big picture

Prerequisite

There is one prerequisite to comply before starting playing around with the Apache’s URL redirection, the Apache’s mod_rewrite must be enabled.

This step is mandatory and because of that it was covered on a previous article.

Actual files

In this particular case, for our simple test of Apache mod_rewrite, three of the files you saw in the big picture are located in the same place, see image below.

vHost.conf file

Apache will seek into the defined directory to find the .htaccess file, if the file exist and the “AllowOverride All” directive is present on the Virtual Host file, then Apache will read and apply the rule/s.

“AllowOverride All” directive and directory where it applies

.htaccess file

As you can see in the image below, the “redirection rule” is defined inside the .htaccess file.

Redirection rule

Regular expressions used in the rewrite rule

RewriteEngine On

RewriteRule ^index.html$ test.html

The caret symbol “^” means “the string starts with”

Caret symbol meaning

The dollar sign $ means “the string ends with”

Dollar sign meaning

index.html file – code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Welcome Index</title>
  </head>
  <body>
    <h1>Index.htm Success! </h1>
  </body>
</html>

index.html file – page

test.html file – code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Test</title>
  </head>
  <body>
    <h1>Mod_Rewrite first URL rewrite</h1>
  </body>
</html>

test.html file – page

Success!!! Apache URL redirection completed

Conclusion

Making use of the mod_rewrite module, and the related files and configurations, Apache was able to redirect the default URL pointing to “index.html” to the “test.html” file, and this concludes our article covering the use of mod_rewrite making a simple URL redirection.