Softpanorama

May the source be with you, but remember the KISS principle ;-)
Contents Bulletin Scripting in shell and Perl Network troubleshooting History Humor

Apache .htaccess file

News Apache Webserver Recommended Links Server Side Includes (SSI) Modules
Mod_rewrite mod_security Using deny directive in apache .htaccess Blocking bad referrers  
  Apache Security Sysadmin Horror Stories Humor Etc

.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof. It is widely used by ISP to provide users with control of their environment which shared hosting environment. Among typical usages:

Note: If you want to call your .htaccess file something else, you can change the name of the file using the AccessFileName directive. For example, if you would rather call the file .config then you can put the following in your server configuration file:

AccessFileName .config

What you can put in these files is determined by the AllowOverride directive. This directive specifies, in categories, what directives will be honored if they are found in a .htaccess file. If a directive is permitted in a .htaccess file, the documentation for that directive will contain an Override section, specifying what value must be in AllowOverride in order for that directive to be permitted.

For example, if you look at the documentation for the AddDefaultCharset directive, you will find that it is permitted in .htaccess files. (See the Context line in the directive summary.) The Override line reads "FileInfo". Thus, you must have at least "AllowOverride FileInfo" in order for this directive to be honored in .htaccess files.

Example:

Context: server config, virtual host, directory, .htaccess
Override: FileInfo

If you are unsure whether a particular directive is permitted in a .htaccess file, look at the documentation for that directive, and check the Context line for ".htaccess."

When (not) to use .htaccess files

In general, you should never use .htaccess files unless you don't have access to the main server configuration file. There is, for example, a prevailing misconception that user authentication should always be done in .htaccess files. This is simply not the case. You can put user authentication configurations in the main server configuration, and this is, in fact, the preferred way to do things.

.htaccess files should be used in a case where the content providers need to make configuration changes to the server on a per-directory basis, but do not have root access on the server system. In the event that the server administrator is not willing to make frequent configuration changes, it might be desirable to permit individual users to make these changes in .htaccess files for themselves. This is particularly true, for example, in cases where ISPs are hosting multiple user sites on a single machine, and want their users to be able to alter their configuration.

However, in general, use of .htaccess files should be avoided when possible. Any configuration that you would consider putting in a .htaccess file, can just as effectively be made in a <Directory> section in your main server configuration file.

There are two main reasons to avoid the use of .htaccess files.

Note that it is completely equivalent to put a .htaccess directives is the appropriate Directory section <Directory /www/htdocs/example> in your main server configuration if of couse you have access to it. Id you use Web services provider you don't and have no choice.

Here is an example of two equivalent directives

As we mentioned before putting this configuration in your server configuration file will result in less of a performance hit, as the configuration is loaded once when Apache starts, rather than every time a file is requested.

The use of .htaccess files can be disabled completely in server configuration file by setting the AllowOverride directive to "none"

AllowOverride None

How directives are applied

The configuration directives found in a .htaccess file are applied to the directory in which the .htaccess file is found, and to all its subdirectories.

However, if there are  .htaccess files in subdirectories they will overwrite settings of the .htaccess file in a particular directory. And those, in turn, may have overridden directives found yet higher up, or in the main server configuration file itself.

Example:

In the directory /www/htdocs/example1 we have a .htaccess file containing the following:

Options +ExecCGI

(Note: you must have "AllowOverride Options" in effect to permit the use of the "Options" directive in .htaccess files.)

In the directory /www/htdocs/example1/example2 we have a .htaccess file containing:

Options Includes

Because of this second .htaccess file, in the directory /www/htdocs/example1/example2, CGI execution is not permitted, as only Options Includes is in effect, which completely overrides any earlier setting that may have been in place.

Authentication example

If you jumped directly to this part of the document to find out how to do authentication, it is important to note one thing. There is a common misconception that you are required to use .htaccess files in order to implement password authentication. This is not the case. Putting authentication directives in a <Directory> section, in your main server configuration file, is the preferred way to implement this, and .htaccess files should be used only if you don't have access to the main server configuration file. See above for a discussion of when you should and should not use .htaccess files.

Having said that, if you still think you need to use a .htaccess file, you may find that a configuration such as what follows may work for you.

You must have "AllowOverride AuthConfig" in effect for these directives to be honored.

.htaccess file contents:

AuthType Basic
AuthName "Password Required"
AuthUserFile /www/passwords/password.file
AuthGroupFile /www/passwords/group.file
Require Group admins

Note that AllowOverride AuthConfig must be in effect for these directives to have any effect.

Please see the authentication tutorial for a more complete discussion of authentication and authorization.

Server side includes example

Another common use of .htaccess files is to enable Server Side Includes for a particular directory. This may be done with the following configuration directives, placed in a .htaccess file in the desired directory:

Options +Includes
AddType text/html shtml
AddHandler server-parsed shtml

Note that AllowOverride Options and AllowOverride FileInfo must both be in effect for these directives to have any effect.

Please see the SSI tutorial for a more complete discussion of server-side includes.

CGI example

Finally, you may wish to use a .htaccess file to permit the execution of CGI programs in a particular directory. This may be implemented with the following configuration:

Options +ExecCGI
AddHandler cgi-script cgi pl

Alternately, if you wish to have all files in the given directory be considered to be CGI programs, this may be done with the following configuration:

Options +ExecCGI
SetHandler cgi-script

Note that AllowOverride Options must be in effect for these directives to have any effect.

Please see the CGI tutorial for a more complete discussion of CGI programming and configuration.

Troubleshooting

When you put configuration directives in a .htaccess file, and you don't get the desired effect, there are a number of things that may be going wrong.

Most commonly, the problem is that AllowOverride is not set such that your configuration directives are being honored. Make sure that you don't have a AllowOverride None in effect for the file scope in question. A good test for this is to put garbage in your .htaccess file and reload. If a server error is not generated, then you almost certainly have AllowOverride None in effect.

If, on the other hand, you are getting server errors when trying to access documents, check your Apache error log. It will likely tell you that the directive used in your .htaccess file is not permitted. Alternately, it may tell you that you had a syntax error, which you will then need to fix.


Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

HTAccess File Configuration in Debian

Web-based user authentication using HTAccess. Web-based authentication denies web access to visitors who do not give a valid username and password. This feature allows webmasters to restrict access to certain directories.

The following is an example use of the .htaccess file. Let's assume that it resides at /home/www/test/public_html/private/.htaccess

AuthUserFile /home/www/test/public_html/private/.htpasswd
AuthGroupFile /dev/null
AuthName "test Secret Section"
AuthType Basic

<Limit GET POST>
require valid-user
</Limit>

The .htaccess file affects the directory in which it is placed, so in this example, any visitor requesting <URL:http://www.test.com/private/> would be presented with an authentication request.

The .htaccess file also affects directories recursively below it. Therefore, requesting <URL:http://www.test.com/private/evenmore/> would yield the same authentication request unless test/private/evenmore had a .htaccess file of its own.

The first line, starting with AuthUserFile, tells the webserver where to find your username/password file. We'll create that file in a minute. For now, change the AuthUserFile line as necessary for your use.

Notice that the AuthName in the example, "test Secret Section," is used in the authentication request.

Using your favorite text editor, create a file similar to the example, replacing AuthUserFile and AuthName with values for your situation. Be sure to name the file .htaccess.

Now that we understand the basic .htaccess model, how can we specify who is allowed? We'll create an .htpasswd file named in the AuthUserFile line above.

To create an .htpasswd file, go to the directory you specified in AuthUserFile. In the example, this is /home/www/test/public_html/private/. Then use the htpasswd program with the -c switch to create your .htpasswd in the current directory. (You have to do this in ssh)

Type htpasswd -c .htpasswd username to create the file and add "username" as the first user. The program will prompt you for a password, then verify by asking again. You will not see the password when entering it here:

debian% htpasswd -c .mypasswds tacodog
Adding password for user paul
New password: type password
Re-type new password: re-type password

To add more users in the future, use the same command without the -c switch: htpasswd .htpasswd bob will add username "bob" to your .htpasswd file.

To delete users, open the .htpasswd file in a text editor and delete the appropriate lines:

username:v3l0KWx6v8mQM

bob:x4DtaLTqsElC2

Configuring HTAccess

Any COE user may setup a .htaccess file in their 'public_html/' directory and/or in any subdirectory created within that 'server root' directory. The main reasons a user would want to set the .htaccess file up are:

Block access to certain files, except to certain domains (or competely).
Add an experimental or special mime-type
Password protect a private directory

The .htaccess file is basically a on-the-fly addition to our server configuration. It allows you to change some aspects of how the server operates on your files and directories. Note that some things have been blocked in order to keep security as high as possible. The .htaccess file is placed in the directory that it operates on. It changes the permissions/settings for the directory it is in and all sub-directories contained therein. You may put an .htaccess file in a subdirectory of a directory controlled by another .htaccess file and it will happily work. The .htaccess file in the parent directory's settings remain in effect unless overridden in the sub-directory's .htaccess file. This is confusing just to describe so it probably shouldn't be done until you are an expert.

DIRECTIVES YOU CAN ADD TO THE .htaccess FILE


Allow
Deny
Order
Require
AddType
AuthUserFile
AuthGroupFile
AuthType
AuthName
DefaultType
ErrorDocument
ForceType
Options
Satisfy
<Files> </Files>

That seems like a lot but they are really very simple. Further discussion of each follows the examples:

EXAMPLES

NOTE: Users of these directives for domains should remember that DNS lookups must be enabled (on your server) for it to translate 'baddomain.com' to an IP. If DNS lookups aren't on, then use the IP's. ( Ex. 133.123.4. will block every IP starting with the address 133.123.4. )

Example 1. Deny a Domain Access to a Directory.

.htaccess contains:

Order Deny,Allow
Deny from .thisbaddomain.com

Note that the Order directive makes sure that 'Deny's override Allows and not the other way.
Also, 'Allow from all' is the assumed default from our master configuration.

Example 2. Deny a Set of Files to a Domain.

.htaccess contains:

<Files *.gif>
Order Deny, Allow
Deny from .thoseevilpeople.net
</Files>

In this case only .gif files would be 'Deny'ed to anyone from .thoseevilpeople.net and only people from them. Since many people have more than one account (office/home) this is rarely used like this. It is more often used in 'Allow'ing ONLY one domain, like in the next example.

Also, the style of the Container Directives (<File> or <Limit>) is like HTML

Example 3. Allow Only One Domain and One

.htaccess contains:

<Files barney*>
Order Allow, Deny
Deny from all
Allow from .test1.com
Allow from .it
</Files>

Note this example allows only people from 'test1.com's corporate office and people in Italy (.it) to view the files that begin with the letters 'barney'. This includes all sub-directories that contain files beginning with those letters and ALL the files in any directories that happen to begin with 'barney'.
Also, notice that we made 'Allow's come before 'Deny's in the 'Order' so that the all DOESN'T mean ALL.

Example 4. Add a Special Mime-Type to a Directory.

.htaccess contains:

AddType image/x-photoshop PSD

This causes the server to announce *.psd files as Content-Type: image/x-photoshop when sending it to the browser. Hopefully the browser knows that image/x-photoshop means run PhotoShop and give it this file. Normally this is used with a new or being tested Plug-In that doesn't have an entry in our master file yet. If you need this on a permanent basis or think it might be useful to others please send us mail about it so we can add it in for everyone.
Also, this will override current setting which makes 'AddType audio/x-dumbexample JPG' valid! You can change what jpg means in your directories.

Example 5.; Force All Files in a Directory to a Specific Mime-Type.

.htaccess contains:

ForceType image/jpg

The causes ALL files in the directory to be treated as JPEG files. No matter their extension.
Note, can NOT be use in a <Files> </Files> tag!

Example 6. Password Protect a Directory - Simple Form.

.htaccess contains:

AuthName Secret Directory Access
AuthType Basic
Require valid-user
AuthUserFile /home/yourusername/mypasswords/.nameoffile

.nameoffile contains:

user1:asdfasdfasdf2
user2:ergvdsdfef34f

'AuthName' causes the browser to display something like, "Enter username for Secret Directory Access at www.thedomain.com:" 'AuthType Basic' tells it to use the 'AuthUserFile' for authentication. (no other types are currently available.) 'Require valid-user' says to only allow a valid-user, you can also use 'Allow' and 'Deny' to stop certain domains.

The .nameoffile contains simple text usernames followed by a ':' and then encrypted password for that user.

Note that the file '.nameoffile' has a period in front of it and is NOT in the www directories. Putting your password file where it could be downloaded would be a VERY bad idea. It is possible to crack simple passwords (one word or name in all upper or lower case is crackable in seconds!) so it is recommended that you use good sense and pick tough passwords that contain a number, symbol, and letter combination. The dot in front of the file simply hides the file from view during normal file listing on unix systems.

It isn't real security but it does mark the file as special when YOU list it. The permissions on the file should be 644. This means that it can be read/write for you and world readable (webserver). Those people who have a full webserver running under their own userid (ask about this since it only occurs when requested and only on some account types), may set the permissions to 600 and disallow anyone else on the system from reading the files as well.

If you want htaccess file web interface or GUI tools click here

ApacheHtaccess - Create and modify Apache .htaccess files - search.cpan.org

Apache .htaccess tweaking tutorial

In this tutorial we are going to improve our website by tweaking out the .htaccess file. Why I wrote this article? Because on the net I have found many articles about this little beast, but every one of them dealt with a specific issue and not look at the overall usage of these files, or they are just too big when you need to do a thing in little time. So I'm trying to collect all the useful bits of data in a monolithic but slim tutorial, which will be updated as I collect more information. But first, let's see what .htaccess file is…

Here we have the definitions from Wikipedia:

.htaccess (Hypertext Access) is the default name of Apache's directory-level configuration file. It provides the ability to customize configuration directives defined in the main configuration file. The configuration directives need to be in .htaccess context and the user needs appropriate permissions.

Let's now deal with most common issues!

Tweaks Index

(Last updated 28th Feb 2006)

  1. Folders Access Control
  2. Folder Listing
  3. Enable Compression
  4. Hide your files
  5. Customized HTTP 404 error page
  6. Blocking bad referers - No hotlinking
  7. Blocking Bad Bots | Fetchers
  8. Do not show 'www'
  9. Hide scripting language extension
  10. Various Tips & Tricks
  11. Password Protection with htpasswd
  12. Enabling SSI
  13. Changing default page
  14. Avoid 500 error
  15. CheckSpelling directive
  16. Add MD5 Digest
  17. Sources
  18. Tools

1) Folders Access Control

You may want to totally disable access in one folder (for example, you have a directory with programming libraries that are included in your main files: in this case only the main files will access these trought the filesystem, but no one from the web should be able to open it). Well, just create an .htaccess file in that folder and put this in it


#deny all access
deny from all

If you'd like to allow access from one specific IP

#deny all access
deny from all
allow from 10.0.0.1

or from a specific IP range (which you enforce with a bit mask)

allow from 192.168.0.0/24

you can also block a specific file from access

<Files private.html>
Order allow,deny
Deny from all
</Files>

./ Back to Index

2) Folder Listing

If you want to make your folders browsable, then you should add this line in .htaccess file

Options +Indexes +MultiViews +FollowSymlinks

And this one if you have the appropriate module installed on your webserver

<ifmodule mod_autoindex.c>
IndexOptions FancyIndexing
</ifmodule>

You may want to prevent folder listing


IndexIgnore *

3) Enable Compression

You can enable PHP's built in data compression to save bandwidth


<ifModule mod_php4.c>
php_value zlib.output_compression 16386
</ifModule>

./ Back to Index

4) Hide your files

To disable access to a particular file you can use a regular expression and the Files directive to deny access to any file beginning with .ht. You can modify it to deny a specific file (like configuration files, robots.txt, log files and whatever you want)

<Files ~ "^\.ht">
Order allow,deny
Deny from all
Satisfy All
</Files>

./ Back to Index

5) Customized HTTP 404 error page

If you'd like to redirect your visitors every time they catch into an HTTP 404 error, use this code:


ErrorDocument 404 /errors/notfound.html

This redirects the user to /errors/notfound.html whenever a 404 error happen. You can of course redefine also other http errors codes (403, 500… and so on). Read below what I've found here!

Tip: Internet Explorer has a lightly-documented "feature" that stops it from serving any custom 404 error page that is less than 512 bytes long. Your visitors will instead be sent to IE's own 404 page (screenshot), which is generic and suggests they use an MSN search to "look for information on the Internet." That's one way to lose visitors! Make sure your custom 404 error page is over this limit - about 10 full lines of text and HTML should be enough.

./ Back to Index

6) Blocking bad referers - No hotlinking

If you want to block some parts of your site from any bad referer:


<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_REFERER} example\.com [NC,OR]
RewriteCond %{HTTP_REFERER} otherexample\.com
RewriteRule .* - [F]
</ifModule>

Using rewrite engine, you will deny access to all your site from any visitor incoming from badguy.com or othernastywebsite.com

To prevent bandwidth stealing, you can also block access to particular files (images, zip, avi and so on)

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://([-a-z0-9]+\.)?example\.com[NC]
RewriteRule .*\.(zip|mp3|avi|wmv|mpg|mpeg)$ http://www.example.com/images/nohotlink.gif [R,NC,L]
</ifModule>

This says: "If the visitor is not coming from mywebsite.net, then redirect all requests for (zip,mp3,avi,wmv,mpg,mpeg) files to a nice image that says "NO HOTLINKING HERE". Got it? You can redirect to a page, or whatever you want, or you can modify the file extension list to include/exclude other files. CAUTION: when you decide to block image hotlinking, remember that you can potentially block ALL traffic outside your domain scope! For example, if you have a feedburner feed you have to modify the rule to let him get the images … or you feed will look quite nasty!
./ Back to Index

7) Blocking Bad Bots | Fetchers

In some cases you want to block some nasty spiders or site downloaders. Then we have to use mod_rewrite again. Usually bad bots ignore robots.txt directive so you may want to enforce them to a 403 error whenever they try to spider or fetch your website


<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} ^BlackWidow [OR]
RewriteCond %{HTTP_USER_AGENT} ^Bot\ mailto:craftbot@yahoo.com [OR]
RewriteCond %{HTTP_USER_AGENT} ^ChinaClaw [OR]
RewriteCond %{HTTP_USER_AGENT} ^Custo [OR]
RewriteCond %{HTTP_USER_AGENT} ^DISCo [OR]
RewriteCond %{HTTP_USER_AGENT} ^Download\ Demon [OR]
RewriteCond %{HTTP_USER_AGENT} ^eCatch [OR]
RewriteCond %{HTTP_USER_AGENT} ^EirGrabber [OR]
RewriteCond %{HTTP_USER_AGENT} ^EmailSiphon [OR]
RewriteCond %{HTTP_USER_AGENT} ^EmailWolf [OR]
RewriteCond %{HTTP_USER_AGENT} ^Express\ WebPictures [OR]
RewriteCond %{HTTP_USER_AGENT} ^ExtractorPro [OR]
RewriteCond %{HTTP_USER_AGENT} ^EyeNetIE [OR]
RewriteCond %{HTTP_USER_AGENT} ^FlashGet [OR]
RewriteCond %{HTTP_USER_AGENT} ^GetRight [OR]
RewriteCond %{HTTP_USER_AGENT} ^GetWeb! [OR]
RewriteCond %{HTTP_USER_AGENT} ^Go!Zilla [OR]
RewriteCond %{HTTP_USER_AGENT} ^Go-Ahead-Got-It [OR]
RewriteCond %{HTTP_USER_AGENT} ^GrabNet [OR]
RewriteCond %{HTTP_USER_AGENT} ^Grafula [OR]
RewriteCond %{HTTP_USER_AGENT} ^HMView [OR]
RewriteCond %{HTTP_USER_AGENT} HTTrack [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Image\ Stripper [OR]
RewriteCond %{HTTP_USER_AGENT} ^Image\ Sucker [OR]
RewriteCond %{HTTP_USER_AGENT} Indy\ Library [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^InterGET [OR]
RewriteCond %{HTTP_USER_AGENT} ^Internet\ Ninja [OR]
RewriteCond %{HTTP_USER_AGENT} ^JetCar [OR]
RewriteCond %{HTTP_USER_AGENT} ^JOC\ Web\ Spider [OR]
RewriteCond %{HTTP_USER_AGENT} ^larbin [OR]
RewriteCond %{HTTP_USER_AGENT} ^LeechFTP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Mass\ Downloader [OR]
RewriteCond %{HTTP_USER_AGENT} ^MIDown\ tool [OR]
RewriteCond %{HTTP_USER_AGENT} ^Mister\ PiX [OR]
RewriteCond %{HTTP_USER_AGENT} ^Navroad [OR]
RewriteCond %{HTTP_USER_AGENT} ^NearSite [OR]
RewriteCond %{HTTP_USER_AGENT} ^NetAnts [OR]
RewriteCond %{HTTP_USER_AGENT} ^NetSpider [OR]
RewriteCond %{HTTP_USER_AGENT} ^Net\ Vampire [OR]
RewriteCond %{HTTP_USER_AGENT} ^NetZIP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Octopus [OR]
RewriteCond %{HTTP_USER_AGENT} ^Offline\ Explorer [OR]
RewriteCond %{HTTP_USER_AGENT} ^Offline\ Navigator [OR]
RewriteCond %{HTTP_USER_AGENT} ^PageGrabber [OR]
RewriteCond %{HTTP_USER_AGENT} ^Papa\ Foto [OR]
RewriteCond %{HTTP_USER_AGENT} ^pavuk [OR]
RewriteCond %{HTTP_USER_AGENT} ^pcBrowser [OR]
RewriteCond %{HTTP_USER_AGENT} ^RealDownload [OR]
RewriteCond %{HTTP_USER_AGENT} ^ReGet [OR]
RewriteCond %{HTTP_USER_AGENT} ^SiteSnagger [OR]
RewriteCond %{HTTP_USER_AGENT} ^SmartDownload [OR]
RewriteCond %{HTTP_USER_AGENT} ^SuperBot [OR]
RewriteCond %{HTTP_USER_AGENT} ^SuperHTTP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Surfbot [OR]
RewriteCond %{HTTP_USER_AGENT} ^tAkeOut [OR]
RewriteCond %{HTTP_USER_AGENT} ^Teleport\ Pro [OR]
RewriteCond %{HTTP_USER_AGENT} ^VoidEYE [OR]
RewriteCond %{HTTP_USER_AGENT} ^Web\ Image\ Collector [OR]
RewriteCond %{HTTP_USER_AGENT} ^Web\ Sucker [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebAuto [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebCopier [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebFetch [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebGo\ IS [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebLeacher [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebReaper [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebSauger [OR]
RewriteCond %{HTTP_USER_AGENT} ^Website\ eXtractor [OR]
RewriteCond %{HTTP_USER_AGENT} ^Website\ Quester [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebStripper [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebWhacker [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebZIP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Wget [OR]
RewriteCond %{HTTP_USER_AGENT} ^Widow [OR]
RewriteCond %{HTTP_USER_AGENT} ^WWWOFFLE [OR]
RewriteCond %{HTTP_USER_AGENT} ^Xaldon\ WebSpider [OR]
RewriteCond %{HTTP_USER_AGENT} ^Zeus
RewriteRule .* - [F]
</ifModule>

(List taken from here)
./ Back to Index

8) Do not show 'www'

To do this, you can use a simple rewrite rule

<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine on
RewriteCond %{http_host} ^www\.example\.com[nc]
RewriteRule ^(.*)$ http://example.com/$1 [r=301,nc]
</IfModule>

Why removing www? You can read it here.

./ Back to Index

9) Hide scripting language extension

You can improve your security by changing script extensions so your visitors don't know what scripting language you are using:


# Make PHP code look like unknown types
AddType application/x-httpd-php .133t

This way the .133t files will be parsed as PHP files. You must rename your files with the new extension.

10) Various Tips & Tricks

11) Password Protection with htpasswd

This is useful if you want to add password protection to some pages/folders

./ Back to Index

12) Enabling SSI

Use this instructions to enable SSI parsing


AddType text/html .html
AddType text/html .shtml
AddHandler server-parsed .html
AddHandler server-parsed .shtml

13) Changing default page

You can use these instructions to change default page (order is important!)

DirectoryIndex home.html index.htm index.html index.php

14) Avoid 500 Error

By passing the charset you avoid the 500 error display

AddDefaultCharset utf-8

15) CheckSpelling directive

This directive can be useful to auto-correct simple spelling errors in the URL

<IfModule mod_speling.c>
CheckSpelling On
</IfModule>

16) Add MD5 Digest

If you aren't worried about performance issues, you can add a MD5 hash calculation to attach a MIC (Message Integrity Check) on each request. This is useful to check the integrity of the message.

ContentDigest On

Perl

ApacheHtaccess - Create and modify Apache .htaccess files - search.cpan.org

Module Version: 1.4 Source

Apache::Htaccess - Create and modify Apache .htaccess files

SYNOPSIS

        use Apache::Htaccess;

        my $obj = Apache::Htaccess->new("htaccess");
        die($Apache::Htaccess::ERROR) if $Apache::Htaccess::ERROR;

        $obj->global_requires(@groups);

        $obj->add_global_require(@groups);

        $obj->directives(CheckSpelling => 'on');

        $obj->add_directive(CheckSpelling => 'on');
        
        $obj->requires('admin.cgi',@groups);

        $obj->add_require('admin.cgi',@groups);

        $obj->save();
        die($Apache::Htaccess::ERROR) if $Apache::Htaccess::ERROR;

This module provides an object-oriented interface to Apache .htaccess files. Currently the ability exists to read and write simple htaccess files.

new()

        my $obj = Apache::Htaccess->new($path_to_htaccess);

Creates a new Htaccess object either with data loaded from an existing htaccess file or from scratch

save()

        $obj->save();

Saves the htaccess file to the filename designated at object creation. This method is automatically called on object destruction.

global_requires()

        $obj->global_requires(@groups);

Sets the global group requirements. If no params are provided, will return a list of the current groups listed in the global require. Note: as of 0.3, passing this method a parameter list causes the global requires list to be overwritten with your parameters. see add_global_require().

add_global_require()

        $obj->add_global_require(@groups);

Sets a global require (or requires) nondestructively. Use this if you just want to add a few global requires without messing with all of the global requires entries.

requires()

        $obj->requires($file,@groups);

Sets a group requirement for a file. If no params are given, returns a list of the current groups listed in the files require directive. Note: as of 0.3, passing this method a parameter list causes the requires list to be overwritten with your parameters. see add_require().

add_require()

        $obj->add_require($file,@groups);

Sets a require (or requires) nondestructively. Use this if you just want to add a few requires without messing with all of the requires entries.

directives()

        $obj->directives(CheckSpelling => 'on');

Sets misc directives not directly supported by the API. If no params are given, returns a list of current directives and their values. Note: as of 0.2, passing this method a parameter list causes the directive list to be overwritten with your parameters. see add_directive().

add_directive()

        $obj->add_directive(CheckSpelling => 'on');

Sets a directive (or directives) nondestructively. Use this if you just want to add a few directives without messing with all of the directive entries.

TO DO

* rewrite the parser to handle blocks

AUTHOR

Matt Cashner <matt@cre8tivegroup.com> originally created this module, and brian d foy <bdfoy@cpan.org> currently maintains it.

COPYRIGHT

Copyright (C) 2000 by The Creative Group.

This module may be distributed under the terms of Perl itself.

Etc

Configuring Apache webserver with .htaccess file

Apache .htaccess file - short tutorial and the most notable and useful htaccess examples.

The Apache Web server provides a feature called .htaccess file, which provides commands to control a Web site. An .htaccess file is simply a text file containing Apache directives. Those directives apply to the documents in the directory where the .htaccess file is located, and to all subdirectories under it as well. Other .htaccess files in subdirectories may change or nullify the effects of those in parent directories.

You have to be careful when editing .htaccess files, as a small mistake can make your Web site stop working. You should immediately test the site to be sure it works.

You can use any text editor to create or make changes to .htaccess files. Keep in mind that commands in .htaccess files should be placed on one line only, so if your text editor uses word-wrap, make sure it's disabled. Be sure .htaccess file is uploaded in ASCII mode, not BINARY, or it won't work.

Your text editor or operating system may probably not allow to save file as .htaccess. The solution is to save the file as htaccess.txt and upload it to your server. After doing that, you should use your FTP client and rename the file to it's proper name .htaccess

Some sites do not allow use of .htaccess files, since they can slow down a server overloaded with domains if they're all using .htaccess files and some things that .htaccess can do can compromise a server configuration that has been specifically setup by the admin. Just be sure to read their TOS carefully or ask permission from your host.

Here are the most notable and useful .htaccess examples...

Custom error pages

The most common errors are 404 (Not Found) and 500 (Internal Server Error). Design your custom Web pages for these errors (you aren't limited to these errors, you can create an error page for each and every error). Add the following commands to your .htaccess file...
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html
You can name the pages anything you want, and you can place them anywhere you want within your site. The initial slash in the directory location represents the root directory of your site.

Enabling SSI

If you want to use SSI, but can't do so with your current Web host, you can change that with .htaccess file. The following lines tell the server that any file named .shtml should be parsed for server side commands...
AddType text/html .shtml
AddHandler server-parsed .shtml
Options Indexes FollowSymLinks Includes
If you don't care about the performance hit of having all .html files parsed for SSI, change the second line to...
AddHandler server-parsed .shtml .html
If you're going to keep SSI pages with the extension of .shtml, and you want to use SSI on your index pages, you need to add the following line to your .htaccess file...
DirectoryIndex index.shtml index.html
This allows a page named index.shtml to be your default page, and if that isn't found, index.html is loaded.

Redirects

You can use .htaccess file to redirect any request for a specific page to a new page...
Redirect /OldDir/old.html http://site.com/NewDir/new.html
Server-side redirects are very useful for shortening affiliate links. Your visitors won't be turned off by long links that are obviously affiliate links. For example, to create a redirect at the URL:
http://YourSite.com/link
to point to the URL:
http://www.MerchantDomain.com/affil.cgi?12345
put this line in your .htaccess file...
Redirect /link http://www.MerchantDomain.com/affil.cgi?12345

Protecting your bandwidth

"Bandwidth stealing," also known as "hot linking," is linking directly to non-html objects on another server, such as images, electronic books etc. The most common practice of hot linking pertains to another site's images.

To disallow hot linking on your server, create the following .htaccess file and upload it to the folder that contains the images you wish to protect...

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?site.com/.*$ [NC]
RewriteRule \.(gif|jpg)$ - [F]
Replace "site.com" with your own. The above code causes a broken image to be displayed when it's hot linked. If you'd like to display an alternate image in place of the hot linked one, replace the last line with...
RewriteRule \.(gif|jpg)$ http://www.site.com/stop.gif [R,L]
Replace "site.com" and stop.gif with your real names.

Preventing directory listing

Typically servers are setup to prevent directory listing, but often they aren't. If you have a directory full of downloads or images that you don't want people to be able to browse through, add the following line to your .htaccess file...
IndexIgnore * 
The * matches all files. If, for example, you want to prevent only listing of images, use...
IndexIgnore *.gif *.jpg 
The .htaccess file is very obscure and extremely useful when used properly. The above htaccess examples cover only a few possible uses of this powerful tool. For more information, see...
Apache User's Guide
List of Apache Directives you can use for your .htaccess files

Comprehensive guide to .htaccess- intro

An htaccess file is a simple ASCII file.

You may need to CHMOD the htaccess file to 644 or (RW-R--R--). This makes the file usable by the server, but prevents it from being read by a browser, which can seriously compromise your security. (For example, if you have password protected directories, if a browser can read the htaccess file, then they can get the location of the authentication file and then reverse engineer the list to get full access to any portion that you previously had protected. There are different ways to prevent this, one being to place all your authentication files above the root directory so that they are not www accessible, and the other is through an htaccess series of commands that prevents itself from being accessed by a browser, more on that later)

Most commands in htaccess are meant to be placed on one line only, so if you use a text editor that uses word-wrap, make sure it is disabled or it might throw in a few characters that annoy Apache to no end, although Apache is typically very forgiving of malformed content in an htaccess file.

htaccess is an Apache thing. There are similar capabilities for NT servers, though in my professional experience and personal opinion, NT's ability in these areas is severely handicapped. But that's not what we're here for.

htaccess files affect the directory they are placed in and all sub-directories, that is an htaccess file located in your root directory (yoursite.com) would affect yoursite.com/content, yoursite.com/content/contents, etc. It is important to note that this can be prevented (if, for example, you did not want certain htaccess commands to affect a specific directory) by placing a new htaccess file within the directory you don't want affected with certain changes, and removing the specific command(s) from the new htaccess file that you do not want affecting this directory. In short, the nearest htaccess file to the current directory is treated as the htaccess file. If the nearest htaccess file is your global htaccess located in your root, then it affects every single directory in your entire site.

Before you go off and plant htaccess everywhere, read through this and make sure you don't do anything redundant, since it is possible to cause an infinite loop of redirects or errors if you place something weird in the htaccess.

Also...some sites do not allow use of htaccess files, since depending on what they are doing, they can slow down a server overloaded with domains if they are all using htaccess files. I can't stress this enough: You need to make sure you are allowed to use htaccess before you actually use it. Some things that htaccess can do can compromise a server configuration that has been specifically setup by the admin, so don't get in trouble.

Now, onto the tasty morsels...

Error Documents

This seems to be what people think htaccess was meant for, but it is only part of the general use. We'll be getting into progressively more advanced stuff after this.

Successful Client Requests
200 OK
201 Created
202 Accepted
203 Non-Authorative Information
204 No Content
205 Reset Content
206 Partial Content
Client Request Redirected
300 Multiple Choices
301 Moved Permanently
302 Moved Temporarily
303 See Other
304 Not Modified
305 Use Proxy
Client Request Errors
400 Bad Request
401 Authorization Required
402 Payment Required (not used yet)
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable (encoding)
407 Proxy Authentication Required
408 Request Timed Out
409 Conflicting Request
410 Gone
411 Content Length Required
412 Precondition Failed
413 Request Entity Too Long
414 Request URI Too Long
415 Unsupported Media Type
Server Errors
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
505 HTTP Version Not Supported
In order to specify your own ErrorDocuments, you need to be slightly familiar with the server returned error codes. (List to the right). You do not need to specify error pages for all of these, in fact you shouldn't. An ErrorDocument for code 200 would cause an infinite loop, whenever a page was found...this would not be good.

You will probably want to create an error document for codes 404 and 500, at the least 404 since this would give you a chance to handle requests for pages not found. 500 would help you out with internal server errors in any scripts you have running. You may also want to consider ErrorDocuments for 401 - Authorization Required (as in when somebody tries to enter a protected area of your site without the proper credentials), 403 - Forbidden (as in when a file with permissions not allowing it to be accessed by the user is requested) and 400 - Bad Request, which is one of those generic kind of errors that people get to by doing some weird stuff with your URL or scripts.

In order to specify your own customized error documents, you simply need to add the following command, on one line, within your htaccess file:

ErrorDocument code /directory/filename.ext
or
ErrorDocument 404 /errors/notfound.html
This would cause any error code resulting in 404 to be forward to yoursite.com/errors/notfound.html

Likewise with:
ErrorDocument 500 /errors/internalerror.html

You can name the pages anything you want (I'd recommend something that would prevent you from forgetting what the page is being used for), and you can place the error pages anywhere you want within your site, so long as they are web-accessible (through a URL). The initial slash in the directory location represents the root directory of your site, that being where your default page for your first-level domain is located. I typically prefer to keep them in a separate directory for maintenance purposes and in order to better control spiders indexing them through a ROBOTS.TXT file, but it is entirely up to you.

If you were to use an error document handler for each of the error codes I mentioned, the htaccess file would look like the following (note each command is on its own line):

ErrorDocument 400 /errors/badrequest.html
ErrorDocument 401 /errors/authreqd.html
ErrorDocument 403 /errors/forbid.html
ErrorDocument 404 /errors/notfound.html
ErrorDocument 500 /errors/serverr.html

You can specify a full URL rather than a virtual URL in the ErrorDocument string (http://yoursite.com/errors/notfound.html vs. /errors/notfound.html). But this is not the preferred method by the server's happiness standards.

You can also specify HTML, believe it or not!

ErrorDocument 401 "<body bgcolor=#ffffff><h1>You have
 to actually <b>BE</b> a <a href="#">member</A> to view 
this page, Colonel!

The only time I use that HTML option is if I am feeling particularly saucy, since you can have so much more control over the error pages when used in conjunction with xSSI or CGI or both. Also note that the ErrorDocument starts with a " just before the HTML starts, but does not end with one...it shouldn't end with one and if you do use that option, keep it that way. And again, that should all be on one line, no naughty word wrapping!

Now you should have yourself some brand-spanking new error documents...go off and destroy your site to see some of those beautiful ErrorDocuments get pulled up.

(Note: that last part is optional)

Next, we are moving on to password protection, that last frontier before I dunk you into the true capabilities of htaccess. If you are familiar with setting up your own password protected directories via htaccess, you may feel like skipping ahead.

-Tutorial Introduction
-Error Documents
-Password protection
-Enabling SSI via htaccess
-Deny users by IP
-Change your default directory page
-Redirects
-Prevent viewing of htaccess
-Adding MIME types
-Preventing hot linking of your images
-Preventing directory listing
-Conclusion and more information

Password protection

Ever wanted a specific directory in your site to be available only to people who you want it to be available to? Ever got frustrated with the seeming holes in client-side options for this that allowed virtually anyone with enough skill to mess around in your source to get in? htaccess is the answer!

There are numerous methods to password protecting areas of your site, some server language based (such as ASP, PHP or PERL) and client side based, such as JavaScript. JavaScript is not as secure or foolproof as a server-side option, a server side challenge/response is always more secure than a client dependant challenge/response. htaccess is about as secure as you can or need to get in everyday life, though there are ways above and beyond even that of htaccess. If you aren't comfortable enough with htaccess, you can password protect your pages any number of ways, and JavaScript Kit has plenty of password protection scripts for your use.

The first thing you will need to do is create a file called .htpasswd. I know, you might have problems with the naming convention, but it is the same idea behind naming the htaccess file itself, and you should be able to do that by this point. In the htpasswd file, you place the username and password (which is encrypted) for those whom you want to have access.

For example, a username and password of wsabstract (and I do not recommend having the username being the same as the password), the htpasswd file would look like this:

wsabstract:y4E7Ep8e7EYV

Notice that it is UserName first, followed by the Password. There is a handy-dandy tool available for you to easily encrypt the password into the proper encoding for use in the httpasswd file.

For security, you should not upload the htpasswd file to a directory that is web accessible (yoursite.com/.htpasswd), it should be placed above your www root directory. You'll be specifying the location to it later on, so be sure you know where you put it. Also, this file, as with htaccess, should be uploaded as ASCII and not BINARY.

Create a new htaccess file and place the following code in it:

AuthUserFile /usr/local/you/safedir/.htpasswd
AuthGroupFile /dev/null
AuthName EnterPassword
AuthType Basic

require user wsabstract

The first line is the full server path to your htpasswd file. If you have installed scripts on your server, you should be familiar with this. Please note that this is not a URL, this is a server path. Also note that if you place this htaccess file in your root directory, it will password protect your entire site, which probably isn't your exact goal.

The second to last line require user is where you enter the username of those who you want to have access to that portion of your site. Note that using this will allow only that specific user to be able to access that directory. This applies if you had an htpasswd file that had multiple users setup in it and you wanted each one to have access to an individual directory. If you wanted the entire list of users to have access to that directory, you would replace Require user xxx with require valid-user.

The AuthName is the name of the area you want to access. It could anything, such as "EnterPassword". You can change the name of this 'realm' to whatever you want, within reason.

We are using AuthType Basic because we are using basic HTTP authentication.

-Tutorial Introduction
-Error Documents
-Password protection
-Enabling SSI via htaccess
-Deny users by IP
-Change your default directory page
-Redirects
-Prevent viewing of htaccess
-Adding MIME types
-Preventing hot linking of your images
-Preventing directory listing
-Conclusion and more information

Enabling SSI Via htaccess

Many people want to use SSI, but don't seem to have the ability to do so with their current web host. You can change that with htaccess. A note of caution first...definitely ask permission from your host before you do this, it can be considered 'hacking' or violation of your host's TOS, so be safe rather than sorry:

AddType text/html .shtml
AddHandler server-parsed .shtml
Options Indexes FollowSymLinks Includes

The first line tells the server that pages with a .shtml extension (for Server parsed HTML) are valid. The second line adds a handler, the actual SSI bit, in all files named .shtml. This tells the server that any file named .shtml should be parsed for server side commands. The last line is just techno-junk that you should throw in there.

And that's it, you should have SSI enabled. But wait...don't feel like renaming all of your pages to .shtml in order to take advantage of this neat little toy? Me either! Just add this line to the fragment above, between the first and second lines:

AddHandler server-parsed .html

A note of caution on that one too, however. This will force the server to parse every page named .html for SSI commands, even if they have no SSI commands within them. If you are using SSI sparingly on your site, this is going to give you more server drain than you can justify. SSI does slow down a server because it does extra stuff before serving up a page, although in human terms of speed, it is virtually transparent. Some people also prefer to allow SSI in html pages so as to avoid letting anyone who looks at the page extension to know that they are using SSI in order to prevent the server being compromised through SSI hacks, which is possible. Either way, you now have the knowledge to use it either way.

If, however, you are going to keep SSI pages with the extension of .shtml, and you want to use SSI on your Index pages, you need to add the following line to your htaccess:

DirectoryIndex index.shtml index.html

This allows a page named index.shtml to be your default page, and if that is not found, index.html is loaded. More on DirectoryIndex later.

-Tutorial Introduction
-Error Documents
-Password protection
-Enabling SSI via htaccess
-Deny users by IP
-Change your default directory page
-Redirects
-Prevent viewing of htaccess
-Adding MIME types
-Preventing hot linking of your images
-Preventing directory listing
-Conclusion and more information

Deny users by IP

Is there a pesky person perpetrating pain upon you? Stalking your site from the vastness of the electron void? Blockem!

In your htaccess file, add the following code--changing the IPs to suit your needs--each command on one line each:

order allow,deny
deny from 123.45.6.7
deny from 012.34.5.
allow from all

You can deny access based upon IP address or an IP block. The above blocks access to the site from 123.45.6.7, and from any sub domain under the IP block 012.34.5. (012.34.5.1, 012.34.5.2, 012.34.5.3, etc.) I have yet to find a useful application of this, maybe if there is a site scraping your content you can block them, who knows.

You can also set an option for deny from all, which would of course deny everyone. You can also allow or deny by domain name rather than IP address (allow from .javascriptkit.com works for www.javascriptkit.com or virtual.javascriptkit.com, etc.)

-Tutorial Introduction
-Error Documents
-Password protection
-Enabling SSI via htaccess
-Deny users by IP
-Change your default directory page
-Redirects
-Prevent viewing of htaccess
-Adding MIME types
-Preventing hot linking of your images
-Preventing directory listing
-Conclusion and more information

Change your default directory page

Some of you may be wondering, just what in the world is a DirectoryIndex? Well, grasshopper, this is a command which allows you to specify a file that is to be loaded as your default page whenever a directory or url request comes in, that does not specify a specific page. Tired of having yoursite.com/index.html come up when you go to yoursite.com? Want to change it to be yoursite.com/ILikePizzaSteve.html that comes up instead? No problem!

DirectoryIndex filename.html

This would cause filename.html to be treated as your default page, or default directory page. You can also append other filenames to it. You may want to have certain directories use a script as a default page. That's no problem too!

DirectoryIndex filename.html index.cgi index.pl default.htm

Placing the above command in your htaccess file will cause this to happen: When a user types in yoursite.com, your site will look for filename.html in your root directory (or any directory if you specify this in the global htaccess), and if it finds it, it will load that page as the default page. If it does not find filename.html, it will then look for index.cgi; if it finds that one, it will load it, if not, it will look for index.pl and the whole process repeats until it finds a file it can use. Basically, the list of files is read from left to right.

Every once in a while, I use this method for the following needs: Say I keep all my include files in a directory called include, and that I keep all my image files in a directory called images, I don't want people to be able to directory browse through them (even though we can prevent that through another htaccess trick, more later) I would specify a DirectoryIndex entry, in a specific htaccess file for those two directories, for /redirect/index.pl that is a redirect page (as explained here) that redirects a request for those directories to be sent to the homepage. Or I could just specify a directory index of index.pl and upload an index.pl file to each of those directories. Or I could just stick in an htaccess redirect page, which is our next subject!

-Tutorial Introduction
-Error Documents
-Password protection
-Enabling SSI via htaccess
-Deny users by IP
-Change your default directory page
-Redirects
-Prevent viewing of htaccess
-Adding MIME types
-Preventing hot linking of your images
-Preventing directory listing
-Conclusion and more information

Redirects

Ever go through the nightmare of changing significantly portions of your site, then having to deal with the problem of people finding their way from the old pages to the new? It can be nasty. There are different ways of redirecting pages, through http-equiv, javascript or any of the server-side languages. And then you can do it through htaccess, which is probably the most effective, considering the minimal amount of work required to do it.

htaccess uses redirect to look for any request for a specific page (or a non-specific location, though this can cause infinite loops) and if it finds that request, it forwards it to a new page you have specified:

Redirect /olddirectory/oldfile.html http://yoursite.com/newdirectory/newfile.html

Note that there are 3 parts to that, which should all be on one line : the Redirect command, the location of the file/directory you want redirected relative to the root of your site (/olddirectory/oldfile.html = yoursite.com/olddirectory/oldfile.html) and the full URL of the location you want that request sent to. Each of the 3 is separated by a single space, but all on one line. You can also redirect an entire directory by simple using Redirect /olddirectory http://yoursite.com/newdirectory/

Using this method, you can redirect any number of pages no matter what you do to your directory structure. It is the fastest method that is a global affect.

-Tutorial Introduction
-Error Documents
-Password protection
-Enabling SSI via htaccess
-Deny users by IP
-Change your default directory page
-Redirects
-Prevent viewing of htaccess
-Adding MIME types
-Preventing hot linking of your images
-Preventing directory listing
-Conclusion and more information

Prevent viewing of .htaccess file

If you use htaccess for password protection, then the location containing all of your password information is plainly available through the htaccess file. If you have set incorrect permissions or if your server is not as secure as it could be, a browser has the potential to view an htaccess file through a standard web interface and thus compromise your site/server. This, of course, would be a bad thing. However, it is possible to prevent an htaccess file from being viewed in this manner:

<Files .htaccess>
order allow,deny
deny from all
</Files>

The first line specifies that the file named .htaccess is having this rule applied to it. You could use this for other purposes as well if you get creative enough.

If you use this in your htaccess file, a person trying to see that file would get returned (under most server configurations) a 403 error code. You can also set permissions for your htaccess file via CHMOD, which would also prevent this from happening, as an added measure of security: 644 or RW-R--R--

-Tutorial Introduction
-Error Documents
-Password protection
-Enabling SSI via htaccess
-Deny users by IP
-Change your default directory page
-Redirects
-Prevent viewing of htaccess
-Adding MIME types
-Preventing hot linking of your images
-Preventing directory listing
-Conclusion and more information

Adding MIME Types

What if your server wasn't set up to deliver certain file types properly? A common occurrence with MP3 or even SWF files. Simple enough to fix:

AddType application/x-shockwave-flash swf

AddType is specifying that you are adding a MIME type. The application string is the actual parameter of the MIME you are adding, and the final little bit is the default extension for the MIME type you just added, in our example this is swf for ShockWave File.

By the way, here's a neat little trick that few know about, but you get to be part of the club since JavaScript Kit loves you: To force a file to be downloaded, via the Save As browser feature, you can simply set a MIME type to application/octet-stream and that immediately prompts you for the download. I have no idea how that would be useful, but that question has come up in our Forums from time to time, so there ya' go.

-Tutorial Introduction
-Error Documents
-Password protection
-Enabling SSI via htaccess
-Deny users by IP
-Change your default directory page
-Redirects
-Prevent viewing of htaccess
-Adding MIME types
-Preventing hot linking of your images
-Preventing directory listing
-Conclusion and more information

Preventing hot linking of images

Note: This portion of tutorial written by JavaScript Kit

In the webmaster community, "hot linking" is a curse phrase. Also known as "bandwidth stealing" by the angry site owner, it refers to linking directly to non-html objects not on one own's server, such as images, .js files etc. The victim's server in this case is robbed of bandwidth (and in turn money) as the violator enjoys showing content without having to pay for its deliverance. The most common practice of hot linking pertains to another site's images.

Using .htaccess, you can disallow hot linking on your server, so those attempting to link to an image on your site, for example, is shown either the door (a broken image), or the lion's mouth (another image of your choice, such as a "Barbara Streisand" picture- no emails please). There is just one small catch- unlike the rest of the .htaccess functionalities we saw earlier, disabling hot linking also requires that your server supports mod_rewrite. Inquire your web host regarding this.

With all the pieces in place, here's how to disable hot linking of images on your site. Simply add the below code to your .htaccess file, and upload the file either to your root directory, or a particular subdirectory to localize the effect to just one section of your site:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.com/.*$ [NC]
RewriteRule \.(gif|jpg)$ - [F]
Be sure to replace "mydomain.com" with your own. The above code causes a broken image to be displayed when its hot linked.

If you're feeling bitter, you can set things up so an alternate image is displayed in place of the hot linked one. The code for this is:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.com/.*$ [NC]
RewriteRule \.(gif|jpg)$ http://www.mydomain.com/nasty.gif [R,L]

Same deal- replace mydomain.com with your own, plus nasty.gif.

Time to pour a bucket of cold water on hot linking!

-Tutorial Introduction
-Error Documents
-Password protection
-Enabling SSI via htaccess
-Deny users by IP
-Change your default directory page
-Redirects
-Prevent viewing of htaccess
-Adding MIME types
-Preventing hot linking of your images
-Preventing directory listing
-Conclusion and more information

Preventing Directory Listing

Do you have a directory full of images or zips that you do not want people to be able to browse through? Typically a server is setup to prevent directory listing, but sometimes they are not. If not, become self-sufficient and fix it yourself:

IndexIgnore *

The * is a wildcard that matches all files, so if you stick that line into an htaccess file in your images directory, nothing in that directory will be allowed to be listed.

On the other hand, what if you did want the directory contents to be listed, but only if they were HTML pages and not images? Simple says I:

IndexIgnore *.gif *.jpg

This would return a list of all files not ending in .jpg or .gif, but would still list .txt, .html, etc.

And conversely, if your server is setup to prevent directory listing, but you want to list the directories by default, you could simply throw this into an htaccess file the directory you want displayed:

Options +Indexes

If you do use this option, be very careful that you do not put any unintentional or compromising files in this directory. And if you guessed it by the plus sign before Indexes, you can throw in a minus sign (Options -Indexes) to prevent directory listing entirely--this is typical of most server setups and is usually configured elsewhere in the apache server, but can be overridden through htaccess.

If you really want to be tricky, using the +Indexes option, you can include a default description for the directory listing that is displayed when you use it by placing a file called HEADER in the same directory. The contents of this file will be printed out before the list of directory contents is listed. You can also specify a footer, though it is called README, by placing it in the same directory as the HEADER. The README file is printed out after the directory listing is printed.

-Tutorial Introduction
-Error Documents
-Password protection
-Enabling SSI via htaccess
-Deny users by IP
-Change your default directory page
-Redirects
-Prevent viewing of htaccess
-Adding MIME types
-Preventing hot linking of your images
-Preventing directory listing
-Conclusion and more information

Conclusion & More Information

Of course, I can't list every possible use of htaccess here, just the more notable and useful ones (read: for fun and profit). There is a list of Apache Directives you can use for your htaccess files, though not all of them are designed to be used by htaccess. Consult the documentation for the directive you are looking to use and make sure that you can actually use it as an htaccess string.

You should also go through the Apache User's Guide for more detailed information if you are really serious about making your life easier as a webmaster. You don't need to update all 4,000 of the pages on your site individually, by hand, in order to change one file reference...honestly!

In any event, I hope you got a better idea of the power available to you through this relatively simple little Clark Kent-ish file. You really do have the ability to save yourself a lot of time and grief by using htaccess, especially when you add to that the power of SSI and xSSI.

Happy htaccessing! (see? tolja that word was keen!)

-Tutorial Introduction
-Error Documents
-Password protection
-Enabling SSI via htaccess
-Deny users by IP
-Change your default directory page
-Redirects
-Prevent viewing of htaccess
-Adding MIME types
-Preventing hot linking of your images
-Preventing directory listing
-Conclusion and more information



Etc

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available in our efforts to advance understanding of environmental, political, human rights, economic, democracy, scientific, and social justice issues, etc. We believe this constitutes a 'fair use' of any such copyrighted material as provided for in section 107 of the US Copyright Law. In accordance with Title 17 U.S.C. Section 107, the material on this site is distributed without profit exclusivly for research and educational purposes.   If you wish to use copyrighted material from this site for purposes of your own that go beyond 'fair use', you must obtain permission from the copyright owner. 

ABUSE: IPs or network segments from which we detect a stream of probes might be blocked for no less then 90 days. Multiple types of probes increase this period.  

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least


Copyright © 1996-2016 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License.

The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to make a contribution, supporting development of this site and speed up access. In case softpanorama.org is down you can use the at softpanorama.info

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose.

Last modified: October 21, 2017