Rewrite and Redirection by .htaccess

Force www

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$$1 [L,R=301,NC]

Force www in a Generic Way

RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
This works for any domain.

Force non-www

It's still open for debate whether www or non-www is the way to go, so if you happen to be a fan of bare domains, here you go:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$$1 [L,R=301]

Force non-www in a Generic Way

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|off
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$
RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L]


RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Force HTTPS Behind a Proxy

Useful if you have a proxy in front of your server performing TLS termination.
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Force Trailing Slash

RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

Redirect a Single Page

Redirect 301 /oldpage.html
Redirect 301 /oldpage2.html

Alias a Single Directory

RewriteEngine On
RewriteRule ^source-directory/(.*) target-directory/$1

Alias Paths To Script

RewriteEngine On
RewriteRule ^$ index.fcgi/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]

This example has an index.fcgi file in some directory, and any requests within that directory that fail to resolve a filename/directory will be sent to the index.fcgi script. It's good if you want to be handled by (which also supports requests to while maintaining and the like. Redirect an Entire Site

Redirect 301 /

This way does it with links intact. That is will become This is extremely helpful when you are just "moving" a site to a new domain. Source Alias "Clean" URLs This snippet lets you use "clean URLs" -- those without a PHP extension, e.g. instead of
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]