Flexible Broadband Services


Comments

FRONTPAGE WARNING: Any modifications to your .htaccess file can corrupt your extensions and render your site inaccessible. A backup copy of your .htaccess file should be made before you attempt any changes.
FrontPage sites have a .htaccess file in the root directory that is created when the FrontPage extensions are installed. FrontPage users should proceed with caution and make a backup copy of their .htaccess file before making any changes. Incorrect changes to your .htaccess file can result in your site being unreachable

 

What is .htaccess - Read!
Whether or Not to Use .htaccess  - Read!
Creating the .htaccess file
Custom Error Messages
Start Page
SSI Parsing
Redirection
Password Protection
htpasswd
Bandwidth Protection
Restricting Access by Domain Name or IP
Changing MIME-Types
Redirect a Machine Name
Other variables you can put into your .htaccess file.

Apache directives -what it all means
Action
AddDescription
AddEncoding
AddIcon
AddIconByEncoding
AddIconByType
AuthDBMUserFile
ErrorDocument
<Files>
Redirect
RedirectPermanent
RedirectTemp
XBitHack



*Remember that the following coding examples are case sensitive, and the spaces must also be adhered to.

htaccess?
.htaccess is the default name for a file that is used to indicate who can or cannot access the contents of a specific file directory from the Internet or an intranet. The .htaccess file is a configuration file that resides in a directory and indicates which users or groups of users can be allowed access to the files contained in that directory. 
.htaccess was introduced as a directory-level, user authentication method along with the original programs developed for retrieving Web pages over the Internet, such as Hypertext Transfer Protocol daemon. When users type in a Uniform Resource Locator (the name of a Web site they want to go to), the URL begins with "http://". This command is recognized by the underlying Web server software program, HTTPd (for HyperText Transfer Protocol daemon). (A daemon is a program that sits waiting for requests for other programs.) 

The main access control file used by HTTPd is the global access configuration file, which often resides at the root directory of the HTTPd server. .htaccess files are additional, directory-level access control files used by HTTPd. 

When the HTTPd server receives a user's request for a document, it looks in the document's own directory, as well as higher up in the chain of directories for these types of access control files. If it finds .htaccess, it will look there to see whether or not the user is allowed to access the file. Based on the information it finds, it may ask the user for his or her user name and password first, before sending the requested document. 

.htaccess is the default file name used by HTTPd when no other name has been indicated in the HTTPd server's resource configuration file, srm.conf. Another file name can be specified in this file, under the AccessFileName <file>line, where <file> would normally indicate .htaccess or another name. (In Netscape servers, this file name is called .nsconfig, and uses a different syntax from .htaccess.) 


Whether or Not to Use .htaccess
.htaccess is often used in settings where a group network administrator wants to control who views or changes the contents of the directories that relate to his or her groups or users. In these settings, it is not practical or advisable to give the administrator primary access to all of the HTTPd server's functions, and all of its other directories and configuration files. Having the local-level control provided by .htaccess files allows more flexibility for the administrator to create and change directory access controls, as needed. 
Some disadvantages to using .htaccess files have been noted: If an organization has several hundred .htaccess files on several hundred directories, each granting or denying user access to their own contents, it is more difficult for the company's network administrators to prepare a global access or authentication strategy and keep up with changes. Also, .htaccess files can be overwritten very easily, causing problems for users who once could access a directory's contents, but now cannot. Finally, .htaccess files are more likely to be opened or retrieved by unauthorized users. 


Creating the .htaccess file:

Before attempting anything you must have a .htaccess file. This will be in the root of your web server. If there is not one there, open up notepad and save as .htaccess and ftp into the root directory. You will notice that file will be called .htaccess.txt, all you need to do now is rename the file via ftp and remove the extension .txt.


Custom Error Messages:

Open up your .htaccess file or follow the steps above and enter the below changing certain parts to fit your needs.

ErrorDocument [error number] [path]

The Error number is the ID that is universal over the Internet. E.g. A file not found is a 404 message. The path is the file you would like to be directed to when this error occurs. Here is a list of the main errors that can occur:

Error in Client
Number Description
400 Bad Syntax
401 Unauthorized
402 Not Used (Payment Granted)
403 Forbidden
404 Not Found
Error in Server
500 Internal Error
501 Not Implemented
502 Overloaded
503 Gateway Timeout

Examples:

ErrorDocument 404 http://www.example.com/404.html
ErrorDocument 401 http://www.example.com/401.html

You do not have to name the file after the name of the error, this is just to make it easy.


Start Page:

Some people's hosts do not have the default directory page as 'index.html'. This can cause major problems for anyone that is relocating their files to a new host. One way to get around this is to use the '.htaccess' file. You can also change the default page from 'index.html' to 'default.html' or 'haha.html'. Type the following into your text editor then save the file:

DirectoryIndex [file]

Examples:

DirectoryIndex page.html
DirectoryIndex haha.shtml


SSI Parsing:

Here you will see how to make the server parse the files with the specified endings. Decide what file extensions you would like the server to look in for SSI tags then enter the following into your text editor:

AddType text/html [Extension 1] [Extension 2]
AddHandler server-parsed [Extension 1] [Extension 2]

Example:

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

or

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


Redirection:

To redirect one page to another is extremely simple using .htaccess. It is one line of code per redirect.

Redirect /old.html http://www.YourDomain.com/directory/new.html


Password Protection:

Have you ever been to a site, clicked on a link on then you got a dialog box asking for a valid username and password. The answer to that was probably 'yes'. Most people have come across a form of password protection like this. This type of password protection can protect directories and sub-directories. You must choose, what directory you would like to password protect and then think up a username and password. For extra security, when entering a password, you must have in encrypted or jumbled up so no one has any idea what you password is.

AuthUserFile [/absolute/path/to/file]
AuthGroupFile /dev/null
AuthName [Text that prompts the user]
AuthType Basic
<Limit GET POST>
order allow,deny
allow from all
require valid-user
</limit>

The path to the password file (AuthUserFile) must be the full path or absolute path as usually called. This is not - http://www.example.com/.file. You must either search your hosts site for this address or ask an administrator although they should have provided this address when you signed up. The path must also include a '/' at the front.

Example of the .htaccess file:

AuthUserFile /data1/example.com/pete/members/.htpasswd
AuthGroupFile /dev/null
AuthName Please enter a password
AuthType Basic
<Limit GET POST>
order allow,deny
allow from all
require valid-user
</limit>

Example of the .htpasswd file:

bob:uurw3xKh6hdcU
sally:35SDRetuXfhsw


htpasswd:

In order to use password protection you must, first set up another file called:

.htpasswd

Note: The password file - '.htpasswd' is not required to be called '.htpasswd' it could be called: .pass if you wanted. This file must be located in the directory which you would like protected and must contain the usernames and passwords that can access the directory in the following format:

username1:password1
username2:password2

A password is always 13 character long and can be different every time however the above isn't. That is all there is to it. If you have any problems with that one, first check that you have encrypted passwords, and also check with your host that you are allowed to protect directories. Then ask for help at a forum.


Bandwidth Protection:

Have you ever skyrocketed over your allocated bandwidth and you have no idea why. Do you have downloads or lots of images on your site. If so, then it is likely that some other site is linking to your downloads and taking all your bandwidth. If you are serving adds, then you probably won't mind as long as the visitor sees the banners. But usually they won't. So how to you stop these people downloading from your site? Here's how. In your .htaccess file you write some code that makes sure that the referring (Previous) URL was a URL that you want people to be able to download from. Type the following into your text editors changing the necessary parts:

AuthUserFile /dev/null
AuthGroupFile /dev/null
RewriteEngine On
RewriteCond %{HTTP_REFERER} !>http://www.example1.com [NC]
RewriteCond %{HTTP_REFERER} !>http://example1.com [NC]
RewriteCond %{HTTP_REFERER} !>http://www.example2.com [NC]
RewriteCond %{HTTP_REFERER} !>http://www.example3.com [NC]
RewriteCond %{HTTP_REFERER} !>http://200.25.25.100 [NC]
RewriteRule /* http://www.example.com/index.html [R,L]

"RewriteCond %{HTTP_REFERER} !>http://www.example1.com [NC]" is the URL or URLs that the downloads will be allowed from.
"RewriteRule /* http://www.example.com/index.html [R,L]" is the page that the surfer will be redirected to if they do try to download from an unauthorised URL. This file needs to be uploaded in ASCII mode to the directory that contains the downloads that you wish to protect. You change the URL to your own. Remember you must add [NC] after the rewriteCond Phrase and [R,L] after the RewriteRule Phrase.


Restricting Access by Domain Name or IP:

  1. Every directory protected this way should have an index.html file that is given out when a request is made for a list of files in the directory. Without that file, a request for the directory will list all of the files in the directory.
  2. Create a file named .htaccess within your directory (note the leading period). This file is consulted by the Web server to determine whether or not to allow access.

    AuthType Basic

    <Limit GET>
    order deny,allow
    deny from all
    allow from .domain.co.uk
    allow from .domain.com
    </Limit>

    or

    <Limit GET>
    order allow,deny
    deny from 124.24.41
    deny from 205.158.256.213
    allow from all
    </Limit>

    Things to watch out for involving Domain restriction:

    In the case of the example .htaccess file (above) which restricts access to domain.co.uk and domain.com addresses, only hosts which have a valid domain name registered in the Domain Name System (DNS) will be allowed access. If you wish to also allow access to U-M hosts without a DNS entry, you can include the following lines in the .htaccess file (in addition to the existing lines in the example):

    allow from 195.112
    allow from 195.113
    allow from 195.114

    These additional lines must be after the order directive and before the </Limit> tag.


Changing MIME-Types:

Changing Mime-types is easy. Just create a .htaccess file that looks like this:

AddType new-mime-type extension

Here's an example and the here's the .htaccess file used.  

AddType text/plain html


Redirect a Machine Name

FRONTPAGE WARNING: Adding this to your .htaccess will not allow you to publish with FrontPage. You need to keep a copy of your original .htaccess file to replace the modified file when making changes to the site

Add the following to the .htaccess file:

RewriteEngine On
Options +FollowSymlinks
RewriteBase /
# Rewrite Rule for machine.domain-name.net
RewriteCond %{HTTP_HOST} machine.domain-name.net$
RewriteCond %{REQUEST_URI} !machine/
RewriteRule ^(.*)$ machine/$1

This will redirect requests for the machine name machine.domain-name.net to the directory machine on the site domain-na


Action:

Syntax: Action mime-type cgi-script

This directive adds an action, which will activate cgi-script when a file of content type mime-type is requested. It sends the URL and file path of the requested document using the standard CGI PATH_INFO and PATH_TRANSLATED environment variables.


AddDescription:

Syntax: AddDescription string file file...

This sets the description to display for a file, for FancyIndexing. File is a file extension, partial filename, wild-card expression or full filename for files to describe. String is enclosed in double quotes (").
Example:

AddDescription "The planet Mars" /web/pics/mars.gif


AddEncoding:

Syntax: AddEncoding mime-enc extension extension...

The AddEncoding directive adds to the list of filename extensions which filenames may end in for the specified encoding type. Mime-enc is the mime encoding to use for documents ending in extension.
Examples:

AddEncoding x-gzip gz
AddEncoding x-compress Z

This will cause files ending in .gz to be marked as encoded using the x-gzip encoding, and .Z files to be marked as encoded with x-compress.


AddIcon:

Syntax: AddIcon icon name name ...

This sets the icon to display next to a file ending in name for FancyIndexing. Icon is either a (%-escaped) relative URL to the icon, or of the format (alttext,url) where alttext is the text tag given for an icon for non-graphical browsers.

Name is either ^^DIRECTORY^^ for directories, ^^BLANKICON^^ for blank lines (to format the list correctly), a file extension, a wildcard expression, a partial filename or a complete filename.
Examples:

AddIcon (IMG,/icons/image.xbm) .gif .jpg .xbm
AddIcon /icons/dir.xbm ^^DIRECTORY^^
AddIcon /icons/backup.xbm *~

AddIconByType should be used in preference to AddIcon, when possible.


AddIconByEncoding:

Syntax: AddIconByEncoding icon mime-encoding mime-encoding ...

This sets the icon to display next to files with mime-encoding for FancyIndexing. Icon is either a (%-escaped) relative URL to the icon, or of the format (alttext,url) where alttext is the text tag given for an icon for non-graphical browsers.

Mime-encoding is a wildcard expression matching required the content-encoding.
Example:

AddIconByEncoding /icons/compress.xbm x-compress


AddIconByType:

Syntax: AddIconByType icon mime-type mime-type ...

This sets the icon to display next to files of type mime-type for FancyIndexing. Icon is either a (%-escaped) relative URL to the icon, or of the format (alttext,url) where alttext is the text tag given for an icon for non-graphical browsers.

Mime-type is a wildcard expression matching required the mime types.
Example:

AddIconByType (IMG,/icons/image.xbm) image/*


AddType:

Syntax: AddType type ext
Context: .htaccess

The AddType directive allows you to add a mime type to your site.

Example:

AddType application/x-httpd-xx xx


AuthDBMUserFile:

Syntax: AuthDBMUserFile filename

The AuthDBMUserFile directive sets the name of a DBM file containing the list of users and passwords for user authentication. Filename is the absolute path to the user file.

The user file is keyed on the username. The value for a user is the crypt() encrypted password, optionally followed by a colon and arbitrary data. The colon and the data following it will be ignored by the server.

Security: make sure that the AuthDBMUserFile is stored outside the document tree of the web-server; do not put it in the directory that it protects. Otherwise, clients will be able to download the AuthDBMUserFile.

Important compatibility note: The implementation of "dbmopen" in the apache modules reads the string length of the hashed values from the DBM data structures, rather than relying upon the string being NULL-appended. Some applications, such as the Netscape web server, rely upon the string being NULL-appended, so if you are having trouble using DBM files interchangeably between applications this may be a part of the problem.

See also AuthName, AuthType and AuthDBMGroupFile.


ErrorDocument:

Syntax: ErrorDocument error-code document

In the event of a problem or error, Apache can be configured to do one of four things,

  1. behave like NCSA httpd 1.3
  2. output a customized message
  3. redirect to a local URL to handle the problem/error
  4. redirect to an external URL to handle the problem/error

2-4 are configured using ErrorDocument, which is followed by the HTTP response code and a message or URL.

Messages in this context, begin with a single quote ("), which does not form part of the message itself. Apache will sometime offer additional information regarding the problem/error.

URLs will begin with a slash (/) for local URLs, or will be a full URL which the client can resolve.
Examples:

ErrorDocument 500 /cgi-bin/tester
ErrorDocument 404 /cgi-bin/bad_urls.pl
ErrorDocument 401 http://www2.foo.bar/subscription_info.html
ErrorDocument 403 "Sorry can't allow you access today


<Files>:

Syntax: <Files filename> ... </Files>

The <Files> directive provides for access control by filename. It is comparable to the <Directory> directive and <Location> directives. It should be matched with a </Files> directive. Directives that apply to the filename given should be listed within. <Files> sections are processed in the order they appear in the configuration file, after the <Directory> sections and .htaccess files are read, but before <Location> sections.

The filename argument should include a filename, or a wild-card string, where `?' matches any single character, and `*' matches any sequences of characters. Extended regular expressions can also be used, with the addition of the ~ character.
For example:

<Files ~ "\.(gif|jpe?g|png)$">

would match most common Internet graphics formats.

Note that unlike <Directory> and <Location> sections, <Files> sections can be used inside .htaccess files. This allows users to control access to their own files, at a file-by-file level. When used in an .htaccess file, if the filename does not begin with a / character, the directory being applied will be prefixed automatically.


Redirect:

Syntax: Redirect [ status ] url-path url

The status argument is only available in Apache 1.2 or later.

The Redirect directive maps an old URL into a new one. The new URL is returned to the client which attempts to fetch it again with the new address. Url-path a (%-decoded) path; any requests for documents beginning with this path will be returned a redirect error to a new (%-encoded) url beginning with url.
Example:

Redirect /service http://foo2.bar.com/service

If the client requests http://myserver/service/foo.txt, it will be told to access http://foo2.bar.com/service/foo.txt instead.

Note: Redirect directives take precedence over Alias and ScriptAlias directives, irrespective of their ordering in the configuration file. Also, Url-path must be an absolute path, not a relative path, even when used with .htaccess files or inside of <Directory> sections.

If no status argument is given, the redirect will be "temporary" (HTTP status 302). This indicates to the client that the resources is has moved temporarily. The status argument can be used to return other HTTP status codes:

permanent
Returns a permanent redirect status (301) indicating that the resource has moved permanently.
temp
Returns a temporary redirect status (302). This is the default.
seeother
Returns a "See Other" status (303) indicating that the resource has been replaced.
gone
Returns a "Gone" status (410) indicating that the resource has been permanently removed. When this status is used the url argument should be omitted.

Other status codes can be returned by giving the numeric status code as the value of status. If the status is between 300 and 399, the url argument must be present, otherwise it must be omitted. Note that the status must be known to the Apache code (see the function send_error_response in http_protocol.c).


RedirectTemp:

Syntax: RedirectTemp url-path url

This directive makes the client know that the Redirect is only temporary. (Status 302). Exactly equivalent to Redirect temporary

RedirectPermanent

Syntax: RedirectPermanent url-path url
Context: directory, .htaccess

This directive makes the client know that the Redirect is permanent. (Status 301). Exactly equivalent to Redirect permanent


XBitHack:

Syntax: XBitHack status

The XBitHack directives controls the parsing of ordinary html documents. Status can have the following values:

off
No special treatment of executable files.
on
Any file that has the user-execute bit set will be treated as a server-parsed html document.
full
As for on but also test the group-execute bit. If it is set, then set the Last-modified date of the returned file to be the last modified time of the file. If it is not set, then no last-modified date is sent. Setting this bit allows clients and proxies to cache the result of the request.

Other variables you can put into your .htaccess file:

Options +Includes
DirectoryIndex index.html
DirectoryIndex index.htm
DirectoryIndex index.shtml
DirectoryIndex index.sht
DirectoryIndex index.cgi
ScriptAlias /cgi-bin cgi-bin
Alias /icons icons
AddType text/html .html .htm
AddType text/plain .txt
AddType text/richtext .rtx
AddType text/tab-separated-values .tsv
AddType text/x-setext .etx
AddType text/x-server-parsed-html .shtml .sht
AddType application/macbinhex-40 .hqx
AddType application/netalivelink .nel
AddType application/netalive .net
AddType application/news-message-id
AddType application/news-transmission
AddType application/octet-stream .bin .exe
AddType application/oda .oda
AddType application/pdf .pdf
AddType application/postscript .ai .eps .ps
AddType application/remote-printing
AddType application/rtf .rtf
AddType application/slate
AddType application/zip .zip
AddType application/x-mif .mif
AddType application/wita
AddType application/wordperfect5.1
AddType application/x-csh .csh
AddType application/x-dvi .dvi
AddType application/x-hdf .hdf
AddType application/x-latex .latex
AddType application/x-netcdf .nc .cdf
AddType application/x-sh .sh
AddType application/x-tcl .tcl
AddType application/x-tex .tex
AddType application/x-texinfo .texinfo .texi
AddType application/x-troff .t .tr .roff
AddType application/x-troff-man .man
AddType application/x-troff-me .me
AddType application/x-troff-ms .ms
AddType application/x-wais-source .src
AddType application/x-bcpio .bcpio
AddType application/x-cpio .cpio
AddType application/x-gtar .gtar
AddType application/x-shar .shar
AddType application/x-sv4cpio .sv4cpio
AddType application/x-sv4crc .sv4crc
AddType application/x-tar .tar
AddType application/x-ustar .ustar
AddType application/x-director .dcr
AddType application/x-director .dir
AddType application/x-director .dxr
AddType application/x-onlive .sds
AddType application/x-httpd-cgi .cgi
AddType image/gif .gif .GIF
AddType image/ief .ief
AddType image/jpeg .jpeg .jpg .jpe .JPG
AddType image/tiff .tiff .tif
AddType image/x-cmu-raster .ras
AddType image/x-portable-anymap .pnm
AddType image/x-portable-bitmap .pbm
AddType image/x-portable-graymap .pgm
AddType image/x-portable-pixmap .ppm
AddType image/x-rgb .rgb
AddType image/x-xbitmap .xbm
AddType image/x-xpixmap .xpm
AddType image/x-xwindowdump .xwd
AddType audio/basic .au .snd
AddType audio/x-aiff .aif .aiff .aifc
AddType audio/x-wav .wav
AddType audio/x-pn-realaudio .ram
AddType audio/x-midi .mid
AddType video/mpeg .mpeg .mpg .mpe
AddType video/quicktime .qt .mov
AddType video/x-msvideo .avi
AddType video/x-sgi-movie .movie
AddType message/external-body
AddType message/news
AddType message/partial
AddType message/rfc822
AddType multipart/alternative
AddType multipart/appledouble
AddType multipart/digest
AddType multipart/mixed
AddType multipart/parallel
AddType x-world/x-vrml .wrl


Mike Duncan