The .htaccess file is an ASCII text document that can be placed in any directory of your web-site to configure the Apache webserver. The .htaccess file is usually placed in the root directory of a website to restrict access to the documents based on different security criteria. You may place the file in a different directory of the website directory structure to secure certain folders and their contents.

Allowing by IP Address

     The following .htaccess example will allow access only to specified IP addresses, and IP subnets:
#.htaccess
	
		order deny,allow
		deny from all
		allow from 170.65.51.
		allow from 170.65.52.
		allow from 170.65.53.
		allow from 4.48.		# allow from bbn planet IP subnet pool.
		allow from .bbn.com		# allow from bbn domain pool.
	
Note: Use of domain names is not supported on all machines.
Note: The allow is accomplished by doing a strncmp, so in order to actually match bytes, you need to leave off the trailing dot, ie: 128.174.5 will match host 128.174.50.7, whereas 128.174.5. will not.

Restricting by IP Address

     The following .htaccess example is will block access to your site to anyone who is coming from any IP address beginning with 128.23.45 and from the specific IP address 207.158.255.213.
#.htaccess
	
		order allow,deny
		deny from 128.23.45.
		deny from 207.158.255.213
		deny from .evil-hackers.org
		allow from all
	
Note: Use of domain names is not supported on all machines.

     The following .htaccess example will allow access only to specified users (require login authentication):
#.htaccess
	authuserfile /home/userid/public_html/secure/.htpasswd
	authgroupfile /dev/null
	authname "Please Login for Authentication."
	authtype basic
	
		require user visitor jason
		#[or
			# require valid-user
				# any user in .htpasswd]
	
     Once you create this .htaccess file with login authentication, you must also set the password for the users; this will be set in the file we specified in the AuthUserFile we specified above.
	% htpasswd -c .htpasswd visitor
	% htpasswd .htpasswd jason
	% chmod a+r .htpasswd
     The -c switch for the htpasswd command will create the file .htpasswd. The -c switch will not be needed once the file is created or exists.

     For best security, it is recommend that you put the password file somewhere where it cannot be downloaded via the web. One way of doing this is to put the password file in a directory that is itself protected by a .htaccess file, and to put no passwords in the password file for that directory. The reason for this is to protect the file from brute force password attacks on the users' password hashes. The file will not be available until .htaccess is bypassed so it would be an internal user you are protecting from.

     The above example demonstrated user authentication. The following example demonstrates group authentication.
#.htaccess
	authuserfile /home/userid/public_html/secure/.htpasswd
	authgroupfile /home/userid/public_html/secure/.htgroup
	authname "Please Login for Authentication."
	authtype basic
	
		require group managers network
	
#.htgroup
	managers: cisco bob tim jeff kari
	systems: lee joe cisco
	sales: kari tonja
     Note: The Apache web server does not allow you to combine group names and user names in the same .htaccess file. You can combine multiple usernames or multiple groups on the same require line.

     The following is a compilation of the above concepts. Managers can view this page from anywhere, everyone else must be from a golden.net IP address:
#.htaccess
	authuserfile /home/userid/public_html/secure/.htpasswd
	authgroupfile /home/userid/public_html/secure/.htgroup
	authname "Please Login for Authentication."
	authtype basic
	
		order deny,allow
		deny from all
		allow from .golden.net
		require group managers
		satisfy any	#default=all
	

Notes:
authtype is usually set to Basic, since we are using Basic HTTP Authentication.
Other possibilities for NCSA HTTPd 1.5 are PEM, PGP, KerberosV4, KerberosV5,
or Digest.

 is usually set to GET, you may also use POST and PUT.
If you only use GET protection for a CGI script, you may find that the
REMOTE_USER environment variable is not being set when using METHOD="POST",
obviously because the directory isn't protected against POST.

The satisfy directive allows you to specify how access is allowed if you
use both allow and require directives.
all 
	In order to gain access to a directory, the user must satisfy both
	the allow and require directives. 
any 
	Users are only required to meet one of the specified allow or require directives. 


If you want to force a 'save file as' message, you can set
the mime-type to application/octet-stream

     The following .htaccess example will allow you to specify the default document when the directory is requested without a specific document. An example would be "http://www.domain.com/", here, we requested a resource without a specific document. Our .htaccess file will default the request to index.html. This is useful when you want to specify a cgi script instead of an HTML document.
#.htaccess
	DirectoryIndex index.html
     If you place your .htaccess file containing the DirectoryIndex specification in the root directory of your site, it will apply for all sub-directories in your site.

Redirect a Machine Name

#.htaccess
	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-name.net.

Preventing People from Linking to Your Images

#.htaccess
	# Rewrite Rule for images
	RewriteCond %{HTTP_REFERER} 
	RewriteRule ^(.*)$ http://
     You would replace the above with the domain name and path of the page that is referring to your domain. For example: www.their-isp.net/users/mypage/

     The RewriteCond directive states that if the {HTTP_REFERER} matches the URL that follows, then use the RewriteRule directive. The RewriteRule directive will redirect any reference back to the referring web page.

Custom Error Messages

#.htaccess
	ErrorDocument 404	/msg/404.html
	ErrorDocument 401	/msg/401.html
     After "ErrorDocument" specify the error code, followed by a space, and then the path and filename of the .html file you would like to be displayed when the specified error is generated.
Error in Client:
	Number	Description
	400	Bad Syntax
	401	Unauthorized
	402	Not Used (Payment Granted)
	403	Forbidden
	404	Not Found
Error in Server:
	Number	Description
	500	Internal Error
	501	Not Implemented
	502	Overloaded
	503	Gateway Timeout

Setting MIME Types
#.htaccess
	#AddType type/subtype extension
	AddType text/plain .txt
	AddType text/plain doc
	AddType application/zip zip
	AddType application/octet-stream exe
	AddType application/octet-stream bin
	AddType application/x-httpd-cgi .cgi
     In general, the content type application/octet-stream is an excellent choice when there is no appropriate "external viewer." A typical browser will then prompt the user to save the file. However, if there is a more appropriate content type, you should of course use that type instead.
Media Content Type			Comments		

application/activemessage
application/andrew-inset                       
application/applefile
application/atomicmail                         
application/dca-rft                            
application/dec-dx                             
application/mac-binhex40
application/macwriteii			MacWrite Document
application/msword			Microsoft Word Document
application/news-message-id                    
application/news-transmission                  
application/octet-stream       		Use for binary file downloads
application/oda                
application/pdf              		Adobe Acrobat Documents
application/postscript			Postscript 
application/remote-printing                    
application/rtf				Rich Text Format
application/slate                              
application/x-mif   
application/wita                               
application/wordperfect5.1		WordPerfect 5.1 Documents
application/wordperfect6.0		WordPerfect 6.0 Documents
application/x-csh			Potentially dangerous [1]
application/x-dvi			TeX/LaTeX Output (not TeX source)
application/x-hdf
application/x-latex			LaTeX Source
application/x-netcdf
application/x-sh			Potentially dangerous
application/x-tcl			Potentially dangerous
application/x-tex			TeX Source
application/x-texinfo
application/x-troff			Troff Formatter Source
application/x-troff-man			Troff Source, -man argument assumed
application/x-troff-me			Troff Source, -me argument assumed	
application/x-troff-ms			Troff Source, -ms argument assumed 
application/x-wais-source
application/zip				Many users have ZIP helper apps
application/x-bcpio
application/x-cpio			cpio tape format (Unix)
application/x-gtar			gnu tar tape format (Unix)
application/x-shar			Potentially dangerous
application/x-sv4cpio
application/x-sv4crc
application/x-ustar
audio/basic				Sun-style .au format audio
audio/x-aiff				Amiga-format .aiff audio
audio/x-wav				Microsoft Windows-format .wav audio
image/gif				Compuserve GIF 8-bit lossless images
image/ief
image/jpeg				JPEG lossy photographic images
image/png				w3 consortium PNG lossless images
image/tiff				TIFF format images
image/x-cmu-raster
image/x-portable-anymap			netpbm/pbmplus images (any subtype)
image/x-portable-bitmap			netpbm/pbmplus black and white images
image/x-portable-graymap		netpbm/pbmplus grayscale images
image/x-portable-pixmap			netpbm/pbmplus truecolor images
image/x-rgb
image/x-xbitmap				X Window System black and white images
image/x-xpixmap				X Window System color images
image/x-xwindowdump			X Window System screen dump format
message/external-body
message/news
message/partial
message/rfc822
multipart/alternative
multipart/appledouble
multipart/digest
multipart/mixed				Server push
multipart/parallel
text/html				HTML documents
text/x-sgml				SGML documents, not limited to HTML
text/plain				Plain ASCII text
text/richtext				This is not RTF (see above)
text/tab-separated-values		Useful for spreadsheet interchange
text/x-setext
video/mpeg				MPEG video format; common on PCs, Unix
video/quicktime				Apple video format
video/x-msvideo				Microsoft/Intel AVI video format
video/x-sgi-movie

See also: