Common rewrite rules for .htaccess

This article will go over some of the more common rules that are requested for .htaccess and redirection in Linux. This article applies only to Linux and in most cases requires that mod_rewrite be enabled in the site container within Apache.

Redirection to WWW

RewriteEngine on
RewriteCond %{HTTP_HOST} ^mydomain.com [NC]
RewriteRule ^(.*)$ http://www.mydomain.com/$1 [L,R=301]

Prevent hotlinking

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$]
RewriteCondan>%{HTTP_REFERER} !^(www\.)?mydomain.com/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^(images\.)google.com/.*$ [NC]
RewriteRule \.(gif|GIF|jpg|JPG|png|PNG)$
http://www.mydomain.com/images/dontsteal.jpg [R,L]

Force Traffic to SSL site

RewriteEngine on
RewriteCond %{SERVER_PORT} !443$
RewriteRule ^(.*)$ https://www.domain.com:443/$1 [R=301,L]

Sudomain Redirection

RewriteEngine On
RewriteCond %{HTTP_HOST} ^subdomain.mydomain.com$ [NC]
RewriteCond %{REQUEST_URI} !^/subdomain/ [NC]
RewriteRule ^(.*)$ http://subdomain.mydomain.com/subdomain$1 [L]