Noupe Editorial Team August 10th, 2009

The Definitive Guide to htaccess Techniques: Do’s and Don’ts

Of all the elements of web design and coding, htaccess can be one of the most intimidating. After all, it's an incredibly powerful tool and one that has the potential to completely break your site if you're not careful. Below are a dozen basic htaccess techniques and tips to get you started. They're not nearly as intimidating as many people expect, and if you study the code for a few minutes, I'm sure you'll quickly grasp exactly how they work and why. After that are a few bewares and don'ts for working with htaccess to help keep you out of trouble, and some more resources for further working with htaccess.

12 Basic htaccess Tips:

1. Create a custom error page.

.htaccess on a Linux Apache server makes it easy to create your own custom error pages. Just create your custom error page files and then add this code to your .htaccess file:
ErrorDocument 401 /401.php
ErrorDocument 403 /403.php
ErrorDocument 404 /404.php
ErrorDocument 500 /500.php
(Obviously you should replace the "/500.php" or whatever with your own file path and name.)

2. Prevent directory browsing.

If you don't include an index file in a directory, visitors can browse the directory itself. But preventing that is as easy as adding a single line to your .htaccess file:
Options All -Indexes

3. Set the default page of each directory.

If you don't want to use an index page in each directory, you can set the default page visited when someone reaches (like an about page or a page offering the newest content) that directory by adding this:
DirectoryIndex news.html
(And of course you'd replace the "news.html" bit with whatever you want to use as the default.)

4. Set up a 301 redirect.

If you move around the structure of your site and need to redirect some old URLs to their new locations, the following bit of code will do so for you:
Redirect 301 /original/filename.html http://domain.com/updated/filename.html

5. Compress file output with GZIP.

You can add the following code to your htaccess file to compress all of your JavaScript, CSS and HTML files using GZIP.
<IfModule mod_gzip.c>
	mod_gzip_on			Yes
	mod_gzip_dechunk	Yes
	mod_gzip_item_include file			.(html?|txt|css|js|php|pl)$
	mod_gzip_item_include handler		^cgi-script$
	mod_gzip_item_include mime		^text.*
	mod_gzip_item_include mime		^application/x-javascript.*
	mod_gzip_item_exclude mime		^image.*
	mod_gzip_item_exclude rspheader	^Content-Encoding:.*gzip.*
</IfModule>

6. Redirect to a secure https connection

If you want to redirect your entire site to a secure https connection, use the following:
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

7. Block script execution.

You can stop scripts in certain languages from running with this:
Options -ExecCGI
AddHandler cgi-script .pl .py .php .jsp. htm .shtml .sh .asp .cgi
Just replace the types of scripts you want to block.

8. Force a file to download with a "Save As" prompt.

If you want to force someone to download a file instead of opening it in their browser, use this code:
AddType application/octet-stream .doc .mov .avi .pdf .xls .mp4

9. Restrict file upload limits for PHP.

You can restrict the maximum file size for uploading in PHP, as well as the maximum execution time. Just add this:
php_value upload_max_filesize 10M
php_value post_max_size 10M
php_value max_execution_time 200
php_value max_input_time 200
Line one specifies the maximum file size for uploading; line two is the maximum size for post data; line three is the maximum time in seconds a script can run before it's terminated; and line four is the maximum amount of time in seconds a script is allowed to parse input data.

10. Enable File Caching.

Enabling file caching can greatly improve your site's performance and speed. Use the following code to set up caching (changing the file types and time values to suit your site's needs):
#cache html and htm files for one day
<FilesMatch ".(html|htm)

quot;> Header set Cache-Control "max-age=43200" </FilesMatch> #cache css, javascript and text files for one week <FilesMatch ".(js|css|txt)

quot;> Header set Cache-Control "max-age=604800" </FilesMatch> #cache flash and images for one month <FilesMatch ".(flv|swf|ico|gif|jpg|jpeg|png)

quot;> Header set Cache-Control "max-age=2592000" </FilesMatch> #disable cache for script files <FilesMatch ".(pl|php|cgi|spl|scgi|fcgi)

quot;> Header unset Cache-Control </FilesMatch>
(Time shown for max-age is in seconds.)

11. Protect your site from hotlinking.

The last thing you want is for those stealing your content to also be able to embed the images hosted on your server in their posts. It takes up your bandwidth and can quickly get expensive. Here's a way to block hotlinking within htaccess:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://([ -a-z0-9]  .)?domain.com [NC]
RewriteRule .(gif|jpe?g|png)$ - [F,NC,L]
(Of course you'll want to replace the domain.com with your own domain name.)

12. Disguise your file types.

You can disguise all of your file types by making them appear as PHP files. Just insert this snippet in:
ForceType application/x-httpd-php

8 Common htaccess Mistakes and Don'ts:

    • Be careful of spelling- .htaccess is not forgiving of spelling errors.
    • htaccess is case sensitive. If something is shown in the examples with a capital letter, make sure it's capitalized in your htaccess file.
    • Consider your caching needs carefully before setting it up. If your site is almost entirely static, you can set longer cache times. If your site changes daily, make sure you adapt which files will cache for how long. There's nothing worse as a visitor than coming back to a site thinking there's been an update and not seeing it.
    • Don't forget to comment out your notes within the file. This is done by adding a # before the comment line.
    • Always test your site immediately after making any changes to your htaccess file. One mistyped character could make the difference between your site working and being down for hours before you realize what's happened.
    • On that note, always make sure you backup your htaccess file before making any changes. That way, if there is a problem, you can easily swap back in the old file.
    • Make sure any essential htaccess functions you've included are cross-browser compatible. There are certain things some browsers just won't support (one example is with certain methods for forcing file downloads).
    • Remember when protecting a web directory with htaccess, that unless it's restricted to https access, the password could be sniffed (as your authentication will be done over an un-secure connection).

More Resources:

Author: Cameron Chapman

Cameron Chapman is a writer, blogger, copyeditor, and social media addict. She's been designing for more than six years and writing her whole life. If you’d like to connect with her, you can follow her on Twitter or at her Personal Website.
Write for Us! We are looking for exciting and creative articles, if you want to contribute, just send us an email.

Noupe Editorial Team

The jungle is alive: Be it a collaboration between two or more authors or an article by an author not contributing regularly. In these cases you find the Noupe Editorial Team as the ones who made it. Guest authors get their own little bio boxes below the article, so watch out for these.

69 comments

  1. Generally I do not learn post on blogs, but I wish to say that this write-up very pressured me to take a look at and do so! Your writing style has been surprised me. Thank you, quite nice article. Executive Elite, 18a Greycoat Gardens, Greycoat Street, London, SW1P 2QA, 028 2088 0135

  2. OMG, htaccess :( I am definitely no good at writing htaccess rules. Great tutorial BTW, it helped me clear some of my doubts.

  3. The rule to force download doesn’t seem to work. I tried on Firefox and IE9 and I can still open the file on the browser.

  4. Great post, Cameron. You have made a difficult subject look easy. I also like the list of common htaccess mistakes to avoid.

  5. Thank you! htaccess files can be a pain in the you know what and mine has been today. You have helped resolved an annoying issue.

Leave a Reply

Your email address will not be published. Required fields are marked *