Use mod_rewrite to Redirect Your Whole Site

Htaccess, mod_rewrite, and Apache

officer directing traffic on white background
 Fang Xia Nuo/Getty Images

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.

How to Use mod_rewrite to Redirect Your Site

  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 ^(.*)$$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, will be redirected to 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:

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.