Learn more about the world's best-loved Web server, with examplesof Apache's authentication and logging capabilities, and also pay a briefvisit to its unique URL re-writing module.
One of the simplest applications of the rewriting engine is also one of itsmost valuable - the ability to prevent Internet users from using imagesfrom your site on theirs. By carefully using the rewriting rules incombination with server variables, you can set things up so that other Websites attempting to link to images on your site will not be granted access.
Here are the lines you need to add to your configuration file:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*\.jpg$ - [F]
The first directive is obvious - it turns the rewriting engine on. Once theengine is active, HTTP requests are scanned and matched against rules inthe file.
The rules - there may be more than one, and they are interpreted in theorder in which they appear - are specified via regular expressions, as inthe example above. The first parameter following the RewriteRuledirective is a pattern, while the second is the substitution pattern; youcan also add special flags as a third parameter to invoke specificbehaviour.
The rule above matches HTTP requests for images - files with the .jpgextension. Typically, you would replace these URLs with another string;however, I've used a hyphen to indicate that no substitution is totake place. Instead, I've used the [F] flag to have the server return a"403 Forbidden" result to the requestingclient.
By itself, this is not enough - if you left it the way it was, everyrequest for an image would be denied. It's therefore necessary to add acondition which checks whether the request is from another server or not.This can be done by checking the value of the HTTP_REFERER variable, whichwill usually not be empty if the request is coming from another server. TheRewriteCond directive above checks the value of this variable, andactivates the rule only when the HTTP_REFERER variable is not empty.
Another interesting application is using the rewriting engine to point yourWeb server's document root to a different physical location on yourserver's hard drive. For example, if you wanted all requests to the serverto be served from the folder
/this/servers/new/root
rather than
/
you could use this simple rule:
RewriteEngine on
RewriteRule ^/$ /this/servers/new/root/ [R]
The [R] flag is used to indicate redirection.
This are just two simple examples which demonstrate the power of URLrewriting - it gets more complex as you get deeper into it. If you'rereally interested in find out what else you can do with the URL rewritingengine, take a look at Ralf Engelschall's Web site athttp://www.engelschall.com/ , and at the Apache manual athttp://www.apache.org/docs/mod/mod_rewrite.html
And that's about it from me for this week. See you soon!