Web Design Tips: 6 favorite .htaccess tricks

By Posted in - Web Design Tips on November 7th, 2009 0 Comments

.htaccess may be a simple ASCII text file, but it’s a powerful tool used on an Apache Web Server which can alter the configuration of your files and directories. With some simple rewrite rules in your .htaccess file, you can do many advanced features from creating custom error pages to setting timezones and emails.Here are 6 of my favorite .htaccess tricks:

SEO Friendly 301 permanent redirects for bad/old links and moved links  (replace the link in the example with your own)

Redirect 301 /d/file.html http://www.bcdesignsit.com/r/file.html

Prevent Files image/file hotlinking and bandwidth stealing

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www.)?askapache.com/.*$ [NC] RewriteRule .(gif|jpg|swf|flv|png)$ /feed/ [R=302,L]

Block IPs – I have used this one in the past to prevent a stalker from viewing my site

allow from all
deny from
deny from 123.14

Rewrite underscores to hyphens for SEO: According to Matt Cutts from Google, dashes or hyphens are better to use instead of underscores for SEO. If your 200 page site uses underscores in the files names, this .htaccess rule can change that easily and quickly.

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule !.(html|php)$ – [S=4] RewriteRule ^([^_]*)_([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4-$5 [E=uscor:Yes] RewriteRule ^([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4 [E=uscor:Yes] RewriteRule ^([^_]*)_([^_]*)_(.*)$ $1-$2-$3 [E=uscor:Yes] RewriteRule ^([^_]*)_(.*)$ $1-$2 [E=uscor:Yes] RewriteCond %{ENV:uscor} ^Yes$
RewriteRule (.*) http://d.com/$1 [R=301,L]

Password Protect Directories and Files

# to protect a file

<Files secure.php>
AuthType Basic
AuthName “Prompt”
AuthUserFile /home/path/.htpasswd
Require valid-user

# password-protect a directory

AuthType basic
AuthName “This directory is protected”
AuthUserFile /home/path/.htpasswd
AuthGroupFile /dev/null
Require valid-user

Redirect an old domain to a new domain

# redirect from old domain to new domain

RewriteEngine On
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [R=301,L]

Please leave a Comment