A tiny collection of 7 mighty useful and basic htaccess directives

The hypertext access ( .htaccess ) is a directory-level configuration file that defines site-specific settings. It enables the localized fine-tuning of Apache’s universal system-configuration directives.

“The localized .htaccess directives must operate from within a file named .htaccess. The user must have appropriate file permissions to access and/or edit the .htaccess file. Further, .htaccess file permissions should never allow world write access — a secure permissions setting is “644”, which allows universal read access and user-only write access. Finally, .htaccess rules apply to the parent directory and all subdirectories. Thus to apply configuration rules to an entire website, place the .htaccess file in the root directory of the site.” — Perishable Press

Comments in .htaccess code are fashioned on a per-line basis, with each line of comments beginning with a pound sign #.

Below I have compiled a list of 7 directives that I use often. The complete documentation can be found at apache.org directive index

1. RewriteCond Directive and RewriteRule Directive

# Permanently redirect from www domain to non-www domain
# ---------------------------------------------------------------
RewriteEngine on
Options +FollowSymLinks
RewriteCond %{HTTP_HOST} ^www\.domain\.tld$ [NC]
RewriteRule ^(.*)$ http://domain.tld/$1 [R=301,L]

# Conversely, you may redirect from an old domain to new domain
# ---------------------------------------------------------------
RewriteRule ^(.*)$ http://www.new-domain.com/$1 [R=301,L]

2. ErrorDocument

# Establish custom serve error pages
# ---------------------------------------------------------------
ErrorDocument 400 /error.php?type=400
ErrorDocument 401 /error.php?type=401
ErrorDocument 403 /error.php?type=403
ErrorDocument 404 /error.php?type=404
ErrorDocument 500 /error.php?type=500

3. Redirect

# Basic redirect of a single file
# ---------------------------------------------------------------
Redirect 301 /old-dir/old-file.html http://domain.com/new-dir/new-file.html

4. Order Directive

# Redirect visitors to a temporary site during site development
# ---------------------------------------------------------------
ErrorDocument 403 http://sub.domain.com
Order deny,allow
Deny from all
Allow from 72.214.3.999

5 and 6. FilesMatch Directive and Files Directive

# Prevent access to multiple file types ( using simple regular expression )
# ---------------------------------------------------------------
<FilesMatch "\.(sql|fla|psd)$">
Order Deny,Allow
Deny from all
</FilesMatch>


# Prevent viewing of a specific file(s)
# ---------------------------------------------------------------
<Files ~ "secretfile.jpg|anotherfile.psd">
Order Deny,Allow
Deny from all
</Files>

7. AddType Directive

# Forcing browser to dispose a file type
# ---------------------------------------------------------------
AddType application/octet-stream .pdf

Leave a Reply