The .htaccess file

When I started working as a developer, I had no idea what .htaccess file was. I had never heard of it and had not used it. So when  I heard my seniors say things like, “There must be an error in the .htaccess.” or “Check the .htaccess file.”, I was confused.

Working as a developer for two years now, I have come across this file a lot of times. We use this to define paths and url and some project configuration so that we don’t have to make changes on the server configuration. This article is just

So what is .htaccess file? .htaccess is short for Hypertext Access and is a configuration file used by Apache-based web servers. When a .htaccess file is placed in a directory which is  in turn ‘loaded via the Apache Web Server’, then the .htaccess file is detected and executed by the Apache Web Server software. The file will take effect over the entire directory it is placed in and all files and subdirectories within the specified directory. The .htaccess file can be use to enable or disable additional functionality and features of Apache Web Server.

Example of what you can put in .htaccess file

AuthName “Member’s Area Name”

AuthUserFile /path/to/password/file/.htpasswd

AuthType Basic

require valid-user

ErrorDocument 401 /error_pages/401.html

AddHandler server-parsed .html

 

This one sets basic authentication for your website.

 

Several uses of .htaccess file

  • Creating custom URL for your webpages – We can write our custom url easily using Apache’s mod_rewrite module. mod_rewrite is used for rewriting URL at the server level. It enables you to modify the format of the URL you let the clients see. For example the client accesses this link http://www.mywebsite.com/product/1/ but in reality, they are requesting from http://www.mywebsite.com/index.php?category=products&id=1/

    Structure of RewriteRuleRewriteRule Pattern Substitution [OptionalFlags]

    In the example above, RewriteRule would look like:
    RewriteRule ^product/([0-9]+)/?$ index.php?id=$1 [L]

    For more information about mod_rewrite, you can check it here: http://www.workingwith.me.uk/articles/scripting/mod_rewrite

 

  • Authentication – Like in the example above, we can set authentication on this file. We can restrict users from accessing certain sections of the website. The .htaccess passwords are kept in a file called .htpasswd. You should place .htpasswd somewhere not accessible from the public.
  • Custom Error Pages – .htaccess also lets us create custom error pages for our site. We can provide more information and display a better looking web page to the site visitor instead of giving them a generic or plain text error page the server produces.

    Most common error codes you might encounter:

    400 – Bad Request
    401 – Authorization Required
    403 – Forbidden
    404 – File Not Found
    500 – Internal Server Error

    To redirect clients to your custom error page when they get 404 error, you add this on the .htaccess file:
    ErrorDocument 404 /error/filenotfound.html

    You can add several error document for different error codes
    ErrorDocument 500 /error/servererror.html
    ErrorDocument 401 /error/authorizationerror.html

  • Cache control – .htaccess allows you to set expiration for your website’s files for browser caching. This will help your webpage to load faster because it doesn’t need to request the same resources everytime the user request a page.
 Caching with mod_headers
     <IfModule mod_headers.c>
        # WEEK
        <FilesMatch "\.(jpg|jpeg|png|gif|swf)$">
            Header set Cache-Control "max-age=604800, public"
        </FilesMatch>

        # WEEK
        <FilesMatch "\.(js|css|swf)$">
            Header set Cache-Control "max-age=604800"
        </FilesMatch>
    </IfModule>

Caching with mod_expires
    ExpiresActive On
    ExpiresDefault A0
 
    # 1 YEAR
    <FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav)$">
        ExpiresDefault A29030400
    </FilesMatch>
 
    # 1 WEEK
    <FilesMatch "\.(jpg|jpeg|png|gif|swf)$">
        ExpiresDefault A604800
    </FilesMatch>
 
    # 3 HOUR
    <FilesMatch "\.(txt|xml|js|css)$">
        ExpiresDefault A10800"
    </FilesMatch>

For a more detailed guide about working with htaccess, you can check out http://wiht.link/-htaccess as it covers from the basics to troubleshooting..

Resources: