Permanent redirects using htaccess

Filed under: htaccess

Firstly, before you start any rewrites, make sure your rewrite engine is turned on. The following line of code should be one of the first lines in your .htaccess file, before any RewriteCond, RewriteRule and redirect, etc.

RewriteEngine On

To permanently redirect a single page, simply add the line:

redirect 301 old-url new-url

  • “redirect” tells Apache what to do.
  • “301″ is your status code for permanent redirect (status codes are optional, but preferable).
  • “old-url” is the old page you want to redirect.
  • “new-url” is the new landing page when the old-url is requested.

To permanently redirect your root page, for example, you have chosen http://www.yourdomain.com/ as your root page and want all requests to http://yourdomain.com/ to permanently redirect to http://www.yourdomain.com/, use the following code:

RewriteCond %{HTTP_HOST} !^www\..* [NC]
RewriteCond %{HTTP_HOST} !^[0-9]+\.[0-9]+\..+ [NC]
RewriteRule ^(.*) http://www.%{HTTP_HOST}/$1 [R=301,L]

  • First line: If the host doesn’t begin with www.
  • Second line: If the host is not an IP.
  • Third line: Then rewrite the host to have http://www. in front.
divider

Leave a Comment