6 Jun, 2017 09:53pm

The Power of .htaccess Part I

This little guy packs quite a punch. Find out how. (Part One)

During the course of the past week, I embarked on a journey to optimise a particular site. While on this journey, I came to discover the power of a little-considered chap known as the .htaccess file. Many web developers typically use it to define custom error pages and remove that pesky "index.php" in the URL (web address) of a web-based application. Other than just defining custom error pages, though, the .htaccess file is capable of a great deal. It is my hope that this article, and the next few articles on this topic, will prove to be an educational experience for those who may not quite know what the .htaccess file is capable of, and a handy reminder for those who already have some experience working with the .htaccess file.

Before we get too far, I would like to define the primary audience of this series of articles: These articles are primarily meant for web developers, both novice and seasoned developers. However, that is not to say that non-developers won't be able to grasp some of the concepts introduced here since the language used, while slightly technical at certain points, is simple and designed to pique the interest of the reader. So without much ado, let's get cracking.


The Basics

The .htaccess file is a configuration file that is limited for use in Apache servers. This means that it will not work on Nginx or NT(Windows) Servers. There are equivalents to the .htaccess configuration available for Nginx and NT Servers, but due to my limited experience with them, I cannot say much else. The .htaccess file is used to extend the functionality of the default Apache config file(s) and allows a site administrator to have control of a wide range of functionalities.

The .htaccess file (especially for any non-developer readers who have made it this far), is called just that: .htaccess. It is not file.htaccess or 1.htaccess, it is just .htaccess. This is due to Unix-based operating systems treating files that begin with a dot or period or full stop (whichever you prefer) as files that should be hidden and since it is a configuration file, .htaccess should remain hidden. If you don't like the name for whatever reason, there's good news: You can change the name.

You can change the name by, first of all, accessing the main Apache configuration file(s). The location of the file may vary depending on the operating system you're running, but in Ubuntu 16.04 LTS, the file can be found by navigating to /etc/apache2/. The file itself is named apache2.conf. Open this file using your favourite text editor and search for the phrase "AccessFileName". It should look something like this:

 

# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives.  See also the AllowOverride
# directive.
#
AccessFileName .htaccess

 

By changing .htaccess to anything you would like, such as .qwerty, Apache will now look for "additional configuration directives" in any file named .qwerty. This, however, does not mean that the rules syntax (more on that later) do not apply, even after the config file name has been changed. It is also useful to note that the lines beginning with "#" are comments and are thus not considered. Key points to keep in mind after doing this are:

  1. After changing the filename in the Apache conf file, it is important to change the name of any exisiting .htaccess file in your project to match the filename set in the conf file.
  2. In order to ensure the security of your project, the renamed file should always begin with a dot/period/full stop in order for the file to remain hidden.

Configuration

Since this is the introductory part of the series, we shall consider just the basics, and you can't get any more basic than the configuration or layout of the .htaccess file as well as a few concepts to bear in mind. As you may have noted above, mention was made of "index.php" in URLs. This is something that will invariably be encountered by any web developer who uses a (PHP) framework and it, therefore, only makes sense to begin this section by considering the .htaccess file in the context of a PHP framework. Due to my experience, working with them, we shall only consider the CodeIgniter and Laravel PHP frameworks.

In a typical CodeIgniter (version 3.1.4) project, the .htaccess file is found in your_project/application/. Keen readers, and experienced CodeIgniter developers, may point out that I've forgotten about the .htaccess file found in your_project/system/. They are partially right in that this particular .htaccess file has been omitted; but they are partially mistaken in that this omission is completely intentional, and not due to my (sometimes) faulty memory. This is because the effective .htaccess file is the one that is publicly accessible, i.e. the one in the /application/ directory*. This concept is carried over to Laravel, where the initial .htaccess file is found in your_project/public/. A default .htaccess file should look, plus or minus a few lines, like the sample shown below (taken from a newly-created Laravel project):

 


   
        Options -MultiViews
   

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

 

Ignoring all the technical stuff like mod_rewrite.c or mod_negotiation.c, considering the above file highlights the key syntax rules used in writing .htaccess files:

  1. All new rules are to be typed out on a new line. This means that if you favourite text editor has a word wrap feature, you might wish to consider turning it off while typing out your .htaccess file.
  2. All opened tags e.g should be closed; you cannot fail to type even an opening or closing tag bracket (< or >). Failure to do this will cause a server error, as I discovered the hard way.

For those who may not be using a development framework, and thus don't have an out-of-the-box .htaccess file, creating one is a simple task. You'll just need to open your favourite text editor, create a new file and save it as .htaccess.


Having looked at the basic setup of a .htaccess file, its structure as well as its rules of syntax and configuration options in the Apache conf file, we can now move on to more configuration options such as the ones shown in the sample .htaccess file seen above. We shall do this beginning with Part II of this series.

If you have any questions or comments, please feel free, as always, to share them below.


* In CodeIgniter version 4, (in "pre-alpha1" development stage at the time of writing of this article) the directory layout has been modified slightly with the introduction of a /public directory, making the file .htaccess found in this directory the effective one. You can follow the development of this new version of CodeIgniter here.



About Michael

Tech enthusiast. Windows sheep. The author of thought-provoking, informative pieces.

Discover More of Michael's Talks