SoftwarePractice.org: Home | Courseware | Wiki | Archive

Apache configuration tips

From SoftwarePractice.org

Here are a bunch of useful things you can do with Apache configuration files (and .htaccess).

Note that a lot of these examples use mod_rewrite. So, you have to have compiled that into your server. You must also have this line in the relevent section of your httpd.conf:

  RewriteEngine On

Contents

Redirect to canonical URL

It's a good idea to allow your server to respond to mysite.org as well as to www.mysite.org. You can do this by adding an alias in your http.conf, like this:

  ServerName www.mysite.org
  ServerAlias mysite.org

But, you really want requests to the former to redirect to the latter. So, do this:

  RewriteCond %{HTTP_HOST}   !^www\.mysite\.org[NC]
  RewriteCond %{HTTP_HOST}   !^$
  RewriteRule ^/(.*)         http://www.mysite.org/$1 [L,R]

Then, a request to eg http://mysite.org/foo/ will redirect to http://www.mysite.org/foo/

Prevent image hotlinking

Some people have no shame, and will embed images from your site into theirs. At best, this can be mildly annoying. If you have a bandwidth quota and they have a very popular site, it can be very expensive. To stop it, do one of the following.

To prevent hotlinking of all images:

  RewriteCond %{HTTP_REFERER} !^$
  RewriteCond %{HTTP_REFERER} !^http://www.mysite.org/.*$ [NC]
  RewriteRule \.(jpg|gif|png)$ - [F]

In this example, any URL with the matching suffix will result in a browser failure. Images embedded in your site will work fine, as will images that are referenced directly from a browser. Note that this will only work with lower-case suffixes -- add the upper-case versions if you have them.

To prevent hotlinking of a specific directory (an image gallery, for example), do this:

  RewriteCond %{HTTP_REFERER} !^$
  RewriteCond %{HTTP_REFERER} !^http://www.mysite.org/.*$ [NC]
  RewriteRule ^/gallery/albums/ /images/goaway.jpg [L]

In this example, the image at /images/goaway.jpg is a small image that makes it clear that you don't like them hotlinking your images...

Redirects for site moves

Sometimes, you just need to move your site around. In order not to break existing links into your site, you should provide redirects from any old location to a new one. Suppose you moved your photo gallery from /albums/ to /gallery/albums/, for instance, add this to your httpd.conf:

  RewriteRule ^/albums/(.*)$  /gallery/albums/$1 [L,R]

Prevent access to naughty people

If you run a public web-server, there is always going to be some jerk who thinks it's clever to run an automated bot against your site. While there are several ways to deal with this, if you just want Apache to deny the request, do it like this:

  <Directory /usr/www/www.mysite.org/public_html>
    Order Allow,Deny
    Allow from all
    Deny from 24.16.57.39 24.18.49.10
  </Directory>
Personal tools