5 Fun and Practical Htaccess Solutions

5 Fun and Practical Htaccess Solutions

Today we will go over some practical uses of htaccess files that you can use in your web applications.

Requirements

Htaccess files are plain-text configuration files used by the Apache HTTP web server. They allow users to set directory level options without requiring access to the httpd.conf file. As such it is required that your server uses Apache, and a web host that allows htaccess files (the most popular hosts do).

I assume a basic working knowledge of htaccess, but if you need to freshen up check out this article by Joseph Pecoraro

1. Prevent Hotlinking

Hotlinking, or inline linking, is when one web site links directly to an object on another site. This costs the hosting site bandwidth to provide the image on the page of the second site. On popular photo sites this can be a major problem, albeit humorous at times.

There are ways to fix this growing problem using htaccess. First here is the image we are trying to protect.

  RewriteEngine on
  RewriteCond %{HTTP_REFERER} !^$

  #domains that can link to images
  #add as many as you want
    RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?demo.collegeaintcheap.com [NC]
    # RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?noahhendrix.com [NC]
  #show no image when hotlinked
    RewriteRule \.(jpg|png|gif)$ - [NC,F,L]

We will step through this line-by-line.

  1. First we need to turn on the rewrite engine in Apache, this allows us to redirect the user’s request.
  2. Next we start setting our conditions using RewriteCond. This is a function that takes two arguments: TestString and CondPattern. TestString is the string we want to check our CondPattern against (using regular expressions). ${HTTP_REFERER} is a variable provided by Apache that holds the domain the request came from, in this instance we want to allow requests from blank HTTP referrers to protect users who are on a proxy server that sends blank referrers.
  3. Next we set the domains from which we will allow our images to be linked using the same syntax except now we provide a URL. The [NC] flag at the end of the command simply instructs the engine to ignore casing. You can add as many lines domains as you’d like here, using the same syntax. For the sake of example I added my personal domain, but commented it out.
  4. Finally, the last line is the RewriteRule we wish to use if any of the conditions above are not met. It takes two arguments as well Pattern and Substitution, where pattern is a regular expression match and substitution is what we want to replace any matches with. In this case we are looking for requests that end in jpg, png, and gif; if found we want to use a blank substitution. However in the flags we tell it furthermore what we want to be done, NC means no case, F sends a 403 forbidden error to user, and L tells the engine to stop rewriting so no other rules are applied.

This is fairly straightforward, but perhaps we are interested in telling the user we don’t want them to hotlink our images, so let’s redirect all hotlinked requests to an image instead of sending a 403 forbidden error. This is done by replacing the last line with this code.

  #show an alternate image
    RewriteRule \.(jpg|png|gif)$ http://demo.collegeaintcheap.com/envato/htaccess/hotlink/images/hotlink.jpeg [NC,R,L]

You can change url to any image path you’d like on your domain, but remember it needs to not end in jpg, png, or gif as it will reapply the rule and send the server into a never-ending loop. I chose to use the older .jpeg extension to fix this. The R flag that replaced F simply sends a redirect.

2. Block User By IP Address

This is a great little tip if you have a spammer on your website. If you can find their IP in your logs, simply add it to an htaccess file.

  Order Deny,Allow
  Deny from 24.121.202.23
  # Deny from 0.0.0.0

Using the Order directive in the mod_access module we can specify IPs to deny and allow. Simply using the syntax Deny from IP ADDRESS we can forbid those users from accessing our directory.

3. Error Documents

All production ready sites should use custom error pages for a professional touch. This is easy using the ErrorDocument directive in Apache’s core. A custom page is far better than the default Apache error pages.

  ErrorDocument 404 http://demo.collegeaintcheap.com/envato/htaccess/errors/404.html
  ErrorDocument 403 http://demo.collegeaintcheap.com/envato/htaccess/errors/403.html
  ErrorDocument 500 http://demo.collegeaintcheap.com/envato/htaccess/errors/500.html

ErrorDocument takes two arguments error-code and document. In the code above I created error documents for the 3 most common HTTP errors: 404 not found, 403 forbidden, and 500 server error. Then you can provide the full URL or relative path to your error documents. You could also them redirect to a PHP script that logs the errors in a database or emails them to you (might get annoying though). This is a great way to take control of errors in your web application, be sure to check out Smashing Magazine’s 404 error page showcase for inspiration.

4. Redirect While Performing Upgrades

If you are performing a major site upgrade you most likely should redirect users to a page informing them. This prevents users from seeing broken pages or potential security holes while the application is uploading. One caveat to consider is that we want to allow certain IP addresses into the site for testing before it goes live all of this can be achieved in an htaccess file.

  RewriteEngine on
  RewriteCond %{REQUEST_URI} !/upgrade.html$
  RewriteCond %{REMOTE_HOST} !^24\.121\.202\.30
  RewriteRule $ http://demo.collegeaintcheap.com/envato/htaccess/upgrade/upgrade.html [R=302,L]

We are using the rewrite engine again to do this, but in a kind of reverse way. First we need to set a condition that excludes the document describing the upgrade otherwise our server start a never ending loop. Next we exclude a single IP address from being redirected for testing purposes. Finally we use the rewrite rule to send users to an upgrade page. The flags we have looked at before, except this time we setting the redirect to a 302 status code, telling the browser that the page has temporarily moved and to handle caching accordingly. Smashing Magazine, again, has a great showcase of Effective Maintenance Pages.

5. Hiding Directory Listing

For numerous security reasons it is a good idea to restrict directory listing, the default behavior in Apache. This can be done with a simple line in our htaccess file we can prevent visitors from seeing our directory listings.

  Options -Indexes

Now users who request a directory that doesn’t have an index file it will show them a 403 forbidden error page.

Conclusion

These are several of my favorite uses of htaccess. Leave yours in the comments! I am available for help in the comments or on twitter. If there is a great deal of interest, I will do more htaccess tutorials with solutions to your requests in the comments. Thanks for reading!


Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.webcoursesbangkok.com Carl – Web Courses Bangkok Instructor

    Really useful thanks! So the email you received was that to you or a friend, what was the outcome?

  • Dave Kennedy

    htaccess IP blocking…. Yes it’s ok for a few IPs but seriously not a good idea if you have a long list of IPs which will no doubt be the case, the .htaccess is served before every page load, to both whitelist and blacklist IPs. Long lists lead to long waits.

    Addressing most of the comments here as well, using htaccess for seo-pretty urls prob isnt a good solution either, it works but is it maintainable as a site scales? You get so much of this out the box with frameworks that use MVC which in my opinion is a more elegant solution… see the CI screencasts on here for info on that.

    I stopped worrying about hotlinking ages ago and dont think it’s a big enough issue to address, there are legitimate uses for hotlinks such as affiliate schemes or people linking to your site and want an image to link with.

    Error docs, well use MVC again and you can have more meaningful error pages, and finally directory listings… you should have been doing that already anyway!!

  • http://ramaboo.com david

    Get ride of the www in a domain:

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

  • http://ramon.com.ua Ramon

    Well, that’s too common info, IMHO. This can be found anywhere.

  • http://www.crearedesign.co.uk Martyn Web

    I find this useful, Ive only really used the htaccess for redirecting away from the index.php and forcing a www. prefix. Oh, and to provide a custom 404 but thats about it.

    Its good to know that these options are available but I probably wouldn’t bother with these on smaller sites.

  • André

    Another great use of .htaccess you can protect a file or folder by password, also you can use a password file or also you can redirect for PHP manage the file as you want.

    And another great use for this, is to create those blog like links, when you hit the archive button shows like http://www.myaddress.com/articles/2009/07 and this shows all the list of articles of july in year 2009… or just http://www.myaddress.com/showarticle/10 where 10 is the ID of the artcile in the database, showarticle can be just a showarticle.php file for example

  • http://www.troypeterson.com Troy

    Ha! Only a programmer would call an htAccess tutorial “fun” :)
    (btw, they are fun.)

  • Christine

    Thanks for that- I’d forgotten to do the hotlinking thing.

    (b.t.w- for some reason I couldn’t see the Name, Email and URL text in the comments fields here in my Opera browser)

  • http://www.demogeek.com DemoGeek

    Blocking the user by IP address would come in real handy for me (and for many others as well). That way we can ban the user who is clicking on the AdSense ads 400 times and getting people to lose their sleep. It might be a constant effort but could be done and could give us some shield than those dreaded AdSense emails. Make sense?

  • roy

    Great Tutorial,It’s very useful…Thanks!

  • http://www.cybernasha.com Prabin

    if you post article about mode_rewrite then that will be great. Thanks for the article..

  • http://m.vinesa.com hyoori

    Thank you very much!!

  • http://heymrblue.com Tomi

    Thanks!! Great article!

  • http://www.jmsolomon.com James Solomon

    Good tut, but if you wanna see some real crazy Apache tricks, this guys blog is great, http://www.askapache.com

  • http://www.asd.com mary

    If it’s a bright, clear day outside, you may instinctively reach for your sunglasses when you head for the door.. But you probably do think about sunglasses when you go to buy a new pair — whether you walk into the discount store or the Sunglass Hut at the mall, you are immediately struck by the bewildering array of choices before you! The style of the frame and size of the lenses also make a difference. Is that $200 pair of Serengeti sunglasses really any better than a $10 pair from the flea market?

  • http://slapandthink.com S.A.T

    Good tut, very complete, and precise.
    I like it :) Thanks!

  • http://www.dear-lover.com wholesale lingerie

    almost every day i need to read your Article. so good. Thanks for sharing those valuable information .

  • alfred

    I am a newbbie. May I ask one stupid question. Where should the .htacess file should put in to prevent the hotlinking of the images. should be on the same level with the image folder, Am I right?
    If the Image folder we redirected by another .htacess to another level, Then this file where I should put?

  • http://www.dev-hq.co.uk Joe

    I like this tutorial a lot.

  • http://link Gangster92

    We had four videographers present. ,

  • www.leadjewellry.com
  • http://techluck.com/ Mark

    You might consider the image leaching method from the apache site that uses a way for those that don’t have mod rewrite from
    http://httpd.apache.org/docs/1.3/env.html

  • http://www.ideaslight.com wholesale wedding dress

    “it’s so good and very funy article.
    thank you very much”

  • http://www.brettwidmann.com Brett Widmann

    Great solutions! Thanks for the post.

  • Christos

    Hello everyone!

    I have a question concerning .htaccess.
    Is this the best way to hide the xxx.html file names from each url of a static html site?
    Can somebody explain how exactly this is done (or redirect me to a tutorial or something)?
    If htaccess is not the best way, what else can I do?

    Thank you!

  • http://www.nonwoven-fabric.net sunshinefabric

    I like this tutorial a lot.

  • http://learntipsandtricks.com/ Damu

    cool!