Redirecting with the .htaccess

Posted on 23rd May, 2014 Leave a Comment

To redirect www to non www add this to your htaccess file.

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

To redirect all sub-domains to the main domain use this.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(.+)\.mydomain\.co.uk$   [NC]
RewriteRule ^ http://mydomain.co.uk/  [L,R]

To redirect a single sub-domain use this.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^sub-domain\.mydomain\.co.uk$   [NC]
RewriteRule ^ http://mydomain.co.uk  [L,R]

Redirect a single url/folder path

RedirectMatch 301 /old-path-to-file/wrong-path-to-file/(.*) /the-path-to-redirect-to/$1

There are a number of ace tools to help you generate your perfect htaccess file, below is the one I usually use.
www.webconfs.com/htaccess-redirect-generator.php

Leave a Comment

To preserve code added to a comment you can wrap your code in short tags
by using [square brackets]:

  1. PHP use - [php] <?php code here ?> [/php]
  2. CSS use - [css] #code-here {} [/css]
  3. HTML use - [html] <div> code here </div> [/html]
  4. JS use - [js] $(".codeHere") [/js]