Quick Tip: Adding Comments to .htaccess Files

If you’re working on an Apache server, you’ve most likely seen .htaccess files, especially if you’ve used a content management tool like WordPress. These files are incredibly powerful, but can get difficult to navigate as they get bigger. The solution? Separate out different functions with code comments.

Add Comments to Your .htaccess Files

But before we get to that, let’s take a look at…

What is an .htacess File?

.htacess is short for “Hypertext Access”, and it controls a huge number of functions on your site, such as:

  • Automatic page redirects
  • Custom error page setup
  • Password protected folders
  • Custom index files
  • Controlling user access

The location of the .htaccess file in very important, because it will affect the directory it is in, and any subdirectories of that directory. That means if you place a .htaccess file in the root of your site, it will affect the entire site, but if you place it in the “archives” directory, it will only affect that directory and anything located under it.

One thing you’ve probably noticed is that file name is very strange. .htaccess is unlike normal files, which have a name, a period, and an extension (e.g. photo.jpg, setup.exe). Rest assured, I have not mistyped it here.

Why Do You Need Comments?

Strictly speaking, you don’t really need comments in your code. They don’t change the way the code works, and thus have no practical affect. They do, however, make working with the files substantially easier. It’s easy enough to find information on a document that’s only 50 lines long or so, but once the page grows into the hundreds and thousands of lines, navigating around becomes much more complicated.

By adding comments to your code, you can categorize the information and make things substantially easier to find. In the case of .htacess files, you can group all your custom error pages into one section, with a comment for a header. Under that, you might include a list of all 301 redirects, using another comment as a header. Well organized and commented code is easy to review and maintain.

How to Add Comments to .htaccess Files

Commenting .htaccess files is very easy. To make a line a comment, simply begin the line with a hash tag (#). Comments in .htaccess files can’t span multiple lines, so if you have longer comments, you have to start each new line with another hash.

Example

# Error Pages
ErrorDocument 404 /errors/404.htm
ErrorDocument 500 /errors/500.htm

#301 Redirects
Redirect 301 /old-url-1.htm http://www.yoursite.com/new-url-1/
Redirect 301 /old-url-2.htm http://www.yoursite.com/new-url-2/

It’s a very simple example, obviously, but you can likely see how useful this practice is on larger documents.

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>