Pages

Rewrite and Redirection by .htaccess


Force www


RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$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 ^(.*)$ http://example.com/$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]

Force HTTPS


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 http://www.yoursite.com/newpage.html
Redirect 301 /oldpage2.html http://www.yoursite.com/folder/

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 baz.foo/some/cool/path to be handled by baz.foo/index.fcgi (which also supports requests to baz.foo) while maintaining baz.foo/css/style.css and the like. Redirect an Entire Site


Redirect 301 / http://newsite.com/


This way does it with links intact. That is www.oldsite.com/some/crazy/link.html will become www.newsite.com/some/crazy/link.html. 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. example.com/users instead of example.com/users.php.
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]