.htaccess For All

Tweet

Htaccess (HyperText Access) is a simple configuration file that allows designers, developers and programmers alike to alter the configuration of the Apache Web Server in order to provide additional functionality. Such functionality can include redirecting users, URL re-writes and providing password-protected directories; but it can do so much more.

So let’s begin …

Creating and Uploading an .htaccess File

Creating an .htaccess file is very easy.

Simply open Notepad or a similar text-based program, switch off word-wrap, add the code and save the file in the usual way.

For example, you could call it:

htaccess.txt

Upload the file to the relevant directory on your web server and then rename it like so:

.htaccess

Remember, the .htaccess file should be using 644 permissions and uploaded in ASCII mode. If your .htaccess file does not work, then you should contact your system administrator or web hosting company and ensure they have enabled ‘.htaccess’ within your account, as some web hosting companies do not allow its use without prior permission. Unfortunately, .htaccess will not work on Windows-based servers.

Using .htaccess

It is important to remember that an .htaccess file will affect the directory it is placed in and all resulting sub-directories. Therefore, if you add your ‘.htaccess’ file to the ‘web site root’ then it will affect all subsequent folders like so:

http://www.yourdomain.com/
| -- directory1
| -- directory2
| -- directory3
|    | -- directory3/childdirectory1
|    | -- directory3/childdirectory2
| -- .htaccess
| -- index.html

However, if you place the ‘.htaccess’ file in http://www.yourdomain.com/directory1 then the features of the ‘.htaccess’ will be restricted to that folder and all child folders only. For example:

http://www.yourdomain.com/
| -- directory1
|    | -- directory1/childdirectory1
|    | -- directory1/childdirectory2
|    | -- directory1/childdirectory3
|    |    | -- directory1/childdirectory3/newdirectory1
|    |    | -- directory1/childdirectory3/newdirectory2
|    | -- .htaccess
|    | -- index.html

After editing your .htaccess file on multiple occassions it may look a little complicated so I would recommend implementing comments. To do this, simply place the hash symbol at the beginning of every line like so:

# comment here
# another comment here

Useful Snippets

And to get you started, it’s snippet time …
(although one or two of them are strictly directives for Apache)

Directory Index

You can change a default index file of directory with:

DirectoryIndex welcome.html welcome.php

Custom Error Pages

You can redirect your users to an error page with:

ErrorDocument 404 error.html

And you can extend this like so:

ErrorDocument 400 /400.html
ErrorDocument 401 /401.html
ErrorDocument 403 /403.html
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html
ErrorDocument 502 /502.html
ErrorDocument 504 /504.html

But remember to create your error pages!

Remove the Need for www in Your URL

Keep your site consistent by removing the need for ‘www’ by using:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.yourdomain.com [NC]
RewriteRule ^(.*)$ http://yourdomain.com/$1 [L,R=301]

Set the Time Zone for Your Server

SetEnv TZ Europe/London

Control Access to Files

Most people will remember that .htaccess is most often used to restrict or deny access to individual files and folders and you can do this like so:

deny from all

However, if you would like to be more specific and ban a specific IP address then you could use:

order allow,deny
deny from XXX.XXX.XXX.XXX
allow from all

or alternatively for several IP addresses, you could use:

allow from all
deny from 145.186.14.122
deny from 124.15

301 Permanent Redirects

Worried about those old links? Then try:

Redirect 301 /olddirectory/file.html http://www.domainname.com/newdirectory/file.html

Set the Email Address for the Server Administrator

By using the following code you can specify the default email address for the server administrator:

ServerSignature EMail
SetEnv SERVER_ADMIN webmaster@domain.com

Detecting Tablets and Redirecting

If you would like to redirect tablet-based users to a particular web page or directory, try:

RewriteCond %{HTTP_USER_AGENT} ^.*iPad.*$
RewriteRule ^(.*)$ http://yourdomain.com/folderfortablets [R=301]
RewriteCond %{HTTP_USER_AGENT} ^.*Android.*$
RewriteRule ^(.*)$ http://yourdomain.com/folderfortablets [R=301]

Link Protection

Concerned about hotlinking or simply want to reduce your bandwidth usage? Try experimenting with:

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www.)?domainname.com/ [nc]
RewriteRule .*.(gif|jpg|png)$ http://domainname.com/img/hotlink_f_o.png [nc]

Force “File Save As”

If you would like force users to download files rather than view them in the browser you could use:

AddType application/octet-stream .csv
AddType application/octet-stream .xls
AddType application/octet-stream .doc
AddType application/octet-stream .avi
AddType application/octet-stream .mpg
AddType application/octet-stream .mov
AddType application/octet-stream .pdf

or you simplify this as:

AddType application/octet-stream .avi .mpg .mov .pdf .xls .mp4

Rewrite URLs

If you would like to make your URLs a little easier to read (ie changing content.php?id=92 to content-92.html) you could implement the following ‘rewrite’ rules:

RewriteEngine on
RewriteRule ^content-([0-9]+).html$ content.php?id=$1

Redirect Browser to https

This is always useful for those who have just installed an SSL certificate:

RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Activate SSI

If you want to activate SSI for HTML and or SHTML file types, try:

AddType text/html .html
AddType text/html .shtml
AddHandler server-parsed .html
AddHandler server-parsed .shtml
AddHandler server-parsed .htm

Disable or Enable Directory browsing

# disable directory browsing
Options All -Indexes
# enable directory browsing
Options All +Indexes

Change the Charset and Language headers

For those who want to change the current character set and language for a specific directory use:

AddDefaultCharset UTF-8
DefaultLanguage en-GB

Block Unwanted Referrals

If you want to block unwanted visitors from a particular website or range of websites you could use:

<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteCond %{HTTP_REFERER} website1.com [NC,OR]
 RewriteCond %{HTTP_REFERER} website2.com [NC,OR]
 RewriteRule .* - [F]
</ifModule>

Block Unwanted User Agents

With the following method, you could save your bandwidth by blocking certain bots or spiders from trawling your website:

<IfModule mod_rewrite.c>
SetEnvIfNoCase ^User-Agent$ .*(bot1|bot2|bot3|bot4|bot5|bot6|) HTTP_SAFE_BADBOT
SetEnvIfNoCase ^User-Agent$ .*(bot1|bot2|bot3|bot4|bot5|bot6|) HTTP_SAFE_BADBOT
Deny from env=HTTP_SAFE_BADBOT
</ifModule>

Block Access to a Comprehensive Range of Files

If you want to protect particular files, or even block access to the .htaccess file, try customising the following code:

<Files privatefile.jpg>
 order allow,deny
 deny from all
</Files>

<FilesMatch ".(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$">
 Order Allow,Deny
 Deny from all
</FilesMatch>

And Lastly …

For reasons of security alone, I think the chance to rename the .htaccess file is very useful:

AccessFileName ht.access

In writing this article I have tried to highlight the range of functions htaccess can be used for. Of course, I haven’t covered everything but as you can see, .htaccess might be an old tool but it still has an important role to play in enhancing your website.

 

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Faisal Alim

    Great!!! is there a like button around here

    oh ok found it…

  • http://www.redcliffdesign.com Brandon Knudsen

    Thanks for sharing this. Htaccess is my favorite http mod. This list is everything I use.
    >>bookmark<<

  • Perry

    And what makes you say that .htaccess does not work on Windows based servers?

    You might want to look at this from the official Apache website…
    http://httpd.apache.org/docs/2.0/platform/windows.html

    I’ve been using it for years, mostly for password protection, and it works fine.

    • http://modefour.net Jonathan Hobson

      Howdy
      I was being generic.
      In a production environment Windows based servers typically run Internet Information Server whereas Apache typically runs on Linux servers. By Windows I was implying IIS on Windows, not Apache on Windows.

      So you could say, technically speaking .htaccess only runs on Apache (wherever Apache happens to be installed).
      Thanks for pointing this out though :-)
      Hope that helps.

  • http://jskdesigns.net Josh Kapplan

    Thank you so much for this explanation.
    I am regularly asked to explain/teach about .htaccess. This is a wonderful explanation, better than my attempts.

  • Edmund

    Thank you for the article – very helpful!
    I have a question: In the case of renaming the file, does the following line go into .htaccess or ht.access? If you have 2 files, what goes into each one?
    AccessFileName ht.access
    Thanks.

    • http://modefour.net Jonathan Hobson

      Hi
      Thanks for the nice comments. Much appreciated.

      The snippet you refer to is a directive for the main Apache configuration file.
      Add this code to the Apache configuration file for your web site and then depending on whatever you now want to call the .htaccess file, that is the file’s name.

      So if your Apache configuration file reads “AccessFileName ht.configuration” then your htaccess filename is “ht.configuration”.

      If you are working on a development machine you could even tell Apache that the filename is “htaccess.txt”, but I would not use this name on a production server. Use something less obvious :-)

      Hope that helps

      • itmitică

        #
        # The following lines prevent .htaccess and .htpasswd files from being
        # viewed by Web clients.
        #
        <Files “.ht*”>
        Require all denied
        </Files>

      • itmitică

        Unfriendly commenting system at work :(

        What I meant was this:

        If you change .htaccess to ht.access you should add this in httpd.conf:

        #
        # The following lines prevent ht.access from being
        # viewed by Web clients.
        #
        <Files “ht.access”>
        Require all denied
        </Files>

      • Alex

        Jonathan,
        I realize that you are not suggesting people to do so, but just to clarify, you should NEVER change the file name to “htaccess.txt”. This would make is readable by anyone by default! You could change the file permissions, and they would have to find the file first, but still….don’t do it!
        In my opinion, it is probably not worth any security gain to go through the hassle of changing the name of your .htaccess file unless you have a specific reason to need to do so.
        Lots of good info in your article. Thanks for sharing it. Too bad .htaccess won’t work on windows, it would make my life easier since I work with Windows and Linux servers.

  • Ocho

    Great overview of what apache configs can do!

  • Pål Nes

    Could you do a similar treaty for Nginx? :)

  • http://plus.ly/digideth B. Moore

    Great Article! Got any more awesome htaccess snippets you can share with us?

    Sure would be nice if you had the “Save to Evernote” button :P

  • logudotcom

    It is very useful, thanks

  • http://zenshadow.com/ Trevor Geene

    I had no idea you could detect for Tablets using .htaccess and redirecting. Is there a way to do this for mobile browsers?

    In your final thing about renaming the .htaccess file to ht.access. How does the system know where to look for the file if that line is in the new file.

  • http://niteodesign.com Blake Petersen

    Amazing cheat sheet! Thanks!!!

  • http://fidelguajardo.blogspot.com Fidel Guajardo

    Doesn’t http://adaptive-images.com/ use the .htaccess file to work its magic of selectively sending out the right image based on the requesting device? What technique are they using?

    • http://www.vulytrampolines.com Ben

      RewriteRule .(?:jpe?g|gif|png)$ adaptive-images.php

      They redirect all gif/jpg/png images to a PHP script, which reads in the original filename and actually resizes it using PHP’s GD library for image manipulation. That would be rather resource intensive, especially seeing as they don’t even cache the images on the server (though they do in memory, which wouldn’t last very long). They could cache images on the server simply by appending an extension of the resolution to the file and checking for its existence and file_get_contents($src.$res) or something.

      Thanks for posting that though, its quite interesting. I’ll consider using that for my website, where we have 32% of visitors using iPads or iPhones.

      • http://www.vulytrampolines.com Ben

        Actually they do use caching* nevermind, it was at the end of the file :p

        /* Use the resolution value as a path variable and check to see if an image of the same name exists at that path */
        if (file_exists($cache_file)) { // it exists cached at that size
        if ($watch_cache) { // if cache watching is enabled, compare cache and source modified dates to ensure the cache isn’t stale
        $cache_file = refreshCache($source_file, $cache_file, $resolution);
        }

        sendImage($cache_file, $browser_cache);
        }

  • NVDon

    Is there any recommended book available that covers htaccess and the other control files in Apache? I have found this particular article to be extremely enlightening but also leaving me with a “I want more…” feeling.

    Thanks for the article!

  • http://Nicecookbook,but... DorseyDorsey

    Explaining why each recipe works as it does would help others create and extend the basics enumerated here.

  • Darrin

    This is good information, but what many users may want to know is how to password protect a directory using .htaccess, which in my opinion is one of the most common uses for its implementation. You talked about controlling access to files/directories based on IP. What about password protection so that any IP can access if the user has the right username/password. Thanks!

  • Andy

    Am I correct in thinking that using .htaccess files in your directory structure can affect the performance of the server (i.e. slow it down)? Can anything that is in a .htaccess file simply be included directly in the Apache config file instead, and will this improve server performance?

  • http://www.ollygoldstein.com Olly Goldstein

    Great thanks
    I know all these already but its a really nice article having them all here together
    Olly