Web Design / HTML

  1. Home
  2. Computing & Technology
  3. Web Design / HTML

Use mod_rewrite to Redirect Your Whole Site

Htaccess, mod_rewrite, and Apache

By Jennifer Kyrnin, About.com

Web pages move - that's a fact of Web development. And if you're smart, you use 301 redirects to prevent link rot. But what if you move the entire website? You could go through and manually write a redirect for every file on the site. But that could take a long time. Luckily it's possible to use htaccess and mod_rewrite to redirect an entire website with just a few lines of code.

  1. In the root of your old Web server, edit or create a new .htaccess file using a text editor.
  2. Add the line:
    RewriteEngine ON
  3. The add:
    RewriteRule ^(.*)$ http://newdomain.com/$1 [R=301,L]

This line will take every file requested at your old domain, and append it (with the same filename) to the URL of your new domain. For example, http://www.olddomain.com/filename will be redirected to http://www.newdomain.com/filename. The R=301 tells the server that the redirect is permanent.

That solution is perfect if you've taken your entire site and moved it, intact, to a new domain. But that doesn't happen very often. A more common scenario is that your new domain has new files and directories. But you don't want to lose the customers who remember the old domain and files. So, you should set up your mod_rewrite to redirect all the old files to the new domain:

RewriteRule ^.*$ http://newdomain.com/ [R=301,L]

As with the previous rule, the R=301 makes this a 301 redirect. And the L tells the server that this is the last rule.

Once you've set up your rewrite rule in the htaccess file, your new website will get all the pageviews from the old URL.

Explore Web Design / HTML

About.com Special Features

Build Your Own Website

Step-by-step advice on how to do everything from choosing a Web host to promoting your content. More >

Connect Your Home Computers

Easy ways to connect two computers for networking purposes. More >

Web Design / HTML

  1. Home
  2. Computing & Technology
  3. Web Design / HTML
  4. Web Server Management
  5. Apache
  6. mod_rewrite
  7. Use mod_rewrite to Redirect Your Whole Site - mod_rewrite Can Redirect Your Website

©2009 About.com, a part of The New York Times Company.

All rights reserved.