Password protect a hotlinked file with Apache

Posted in Apache -

In one of my posts I have an AJAX loading image to demonstrate showing a loading image while waiting for an AJAX request to run. For some reason a bunch of people have decided to hotlink the loading image from my site, rather than generate their own from and host it themselves.

There are many websites out there offering how to prevent hotlinking by using rewrite rules to show either a different image or make it forbidden (here's a good tutorial) but I decided to do it differently and pop up a username and password dialog instead.

Showing a username and password dialog - why?

It was only one file, linked to from my page on my website so it was easy enough to simply rename it.

If my webserver returns a 404 (file not found) or 403 (forbidden) code then all the user is going to see is a broken image and there's a good chance the people who own the website will do nothing about it.

I could make a different image display instead - I've often seen people suggest putting up some sort of advertising, an obscene image, or some text in the image saying that the website owner is a bandwidth thief - but don't want to lose more bandwidth.

Renaming the image and "password protecting" the old image can be a quick and easy solution, loses little bandwidth (just the HTTP request and 401 return information) and you can still put a message in the username/password dialog.

Why not ask them to remove the hotlinking?

One of the websites hotlinking the image is a university in Australia. I did ask them to stop hotlinking to my image but the request clearly fell on deaf ears. I can't be bothered trying to contact all the hotlinkers and be ignored so this might get some action. At the very least it will cut down on bandwidth.

Password protecting the file

The old file was named /images/ajax-loader.gif

I added the following to my .htaccess file and now whenever the file is requested on the website hotlinking it, a password protection dialog appears.

<Files ajax-loader.gif>
    AuthName "Restricted Access"
    AuthType Basic
    require user foo

The user "foo" can be anything; it's not really relevent as we're not actually validating against a password file. Change the "Restricted Access" to whatever message you want it to be.

Just one other thing I would note, I did try specifying the full path to the image (i.e. images/ajax-loader.gif) but that didn't seem to work. I guess that the Files directive doesn't allow path separators. So the above directive will match a file named ajax-loader.gif in any directory.

Related posts: