Handy htaccess examples

Repoint all outside IP to external maintenance page

Options +SymLinksIfOwnerMatch
RewriteEngine on
RewriteBase '/'
# IP Address of maintenance to provide access to site
RewriteCond %{REMOTE_ADDR} !^{NNN}\.{NN}\.{NNN}\.{NNN}
RewriteCond %{REQUEST_URI} !^/maintenance\.html$
RewriteRule ^(.*)$ http://www.example.co.nz/maintenance [R=307,L]

Remove part of a URL

Remove text string "~tasmanba"

RewriteRule ^~tasmanba/(.+)$ /$1 [L,QSA]

Remove apostrophe special char

RewriteRule ^content/kid[^s]+s-fish-out-pond-permit http://www.example.org.nz/content/kids-fish-out-pond-permit [R=301,L]

Redirect any url that contains "content"

RewriteCond %{QUERY_STRING} content/
RewriteRule ^ restaurants/? [L,R=301]

Redirect 301 for complete site

Redirect 301 / http://www.example.nz

Redirect specific url to another url

rewriteRule ^dmsdocument/111 /dmsdocument/113 [R=permanent,L]

Redirect all urls containing path to another

RewriteCond %{HTTP_HOST} ^example\.co.nz$
RewriteRule ^(.*)$ http://example.org.nz/example-newsletter/$1 [R=permanent,L]

Redirect multiple domains to parent domains

RewriteCond %{HTTP_HOST} ^example-1\.co\.nz$ [OR]
RewriteCond %{HTTP_HOST} ^www.example-1\.co\.nz$ [OR]
RewriteCond %{HTTP_HOST} ^example-1\.kiwi$
RewriteRule (.*)$ http://www.example-1.kiwi/$1 [R=301,L]

Make all pages apart from those designated to SSL 

RewriteCond %{SERVER_PORT} =443 [NC]
RewriteCond %{REQUEST_URI} ^/url/subURL [OR]
RewriteCond %{REQUEST_URI} URL
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !framework/main.php
RewriteRule ^(.*)$ http://www.example.com/$1 [R=permanent,L]

RewriteCond %{SERVER_PORT} !=443 [NC]
RewriteCond %{REQUEST_URI} !^/url/subURL [NC]
RewriteCond %{REQUEST_URI} !URL [NC]
RewriteCond %{REMOTE_ADDR} !=127.0.0.1
RewriteCond %{REMOTE_ADDR} !=::1
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !framework/main.php
RewriteRule ^(.*)$ https://www.example.com/$1 [R=permanent,L]

Authentication Rules

RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Using WWW or Not (Stolen from Drupal .htaccess)

# To redirect all users to access the site WITH the 'www.' prefix,
# (http://example.com/... will be redirected to http://www.example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} !^www\. [NC]
# RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
#
# To redirect all users to access the site WITHOUT the 'www.' prefix,
# (http://www.example.com/... will be redirected to http://example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
# RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301] 

Clean URLS Pass all requests not referring directly to files in the filesystem to index

 RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]