Top Nav

Redirect Old URLS In .htaccess

Frequently when our clients upgrade their website, they will need URLs from the old site mapped to the new site. So for example maybe they had this URL on the old server:

http://acme.com/widgets/egonomic-widget-design

Maybe there are many sites on the Internet that link to this URL so they don’t want it to return a 404 error. Instead they want it to redirect to the new address of the article at:

http://acme.com/smallwidgets/designing-egonomic-widgets

This can be accomplished with a simple rewrite rule in the .htaccess file like this:


RewriteEngine On
Rewriterule ^widgets\/egonomic-widget-design$ http://acme.com/smallwidgets/designing-egonomic-widgets [R=permanent,L]

Note that the RewriteRule should be on one line in the file … not wrapped over two lines.

The pattern for the rewrite rule is:

Also notice that in the source pattern we escaped the slash (/) with a backslash (\). This is necessary since the slash has special meaning in a regular expression.

In the above example, we’re doing a full match of the source url. In some cases you might want more flexibility. For example if you want to redirect:

http://acme.com/folder

to:

http://acme.com/newfolder

Then you might want to use a rule like this:


RewriteEngine On
Rewriterule ^folder(.*)$ http://acme.com/newfolder [R=permanent,L]

The source pattern with match any url starting with “folder”. This way both “folder” and “folder/” will match.

Of course there are many more variations on this type of rewrite rule.