Apache redirect dynamic urls

May 28, 2008

Backgound

Many times there’s a big need to redirect different URL’s on your website to other places. The reason for this can be very different, but the idea is same. We need a reliable way of doing that. Off course that can be done in a “script wise” manner; I mean, if your website is dynamic, upon loading a specific page, the requested URI could be checked against a database redirects collection and if found there, the specific redirect would be issued ( be it a 302 moved temporarily redirect, 301 Permanent redirect, etc. ). That’s beyound the purpose of this article.

So what would be a simple solution to do a temporary/permanent redirect on dynamic URL?

Since I was asked by many peoples over this website and other places to present a way of doing redirects of dynamic URL’s using .htaccess, I decided to put here a way that I found useful.

So here it is the following htaccess file:

RewriteEngine onRewriteCond %{QUERY_STRING} ^page=1$

RewriteRule ^(/)?$ http://mywebsite.com/url_to_go_to [R=301,L]

Basically that would do the trick, and would issue a 301 Redirect of /?page=1 to http://mywebsite.com/url_to_go_to. If you try that you’ll notice a small problem which really is not a problem: The URL to where it gets redirected will be: http://mywebsite.com/url_to_go_to?page=1. Notice that the query string is automatically appended to the new URL. That can be prevented by ending the URL to be redirected to with a ? mark, as stated in the Apache mod_rewrite documentation, where there is explained the query-string-clearing function.

When you want to erase an existing query string, end the substitution string with just the question mark “

If you are trying to redirect an URL like /index. php?page=2 to something like http://www.mysite.com/page/2 , than you can use the power of regular expressions combined with Apache features.

This will look something like the above:

RewriteEngine onRewriteCond %{QUERY_STRING} ^page=([0-9]*)$

RewriteRule ^(/)?$ http://mywebsite.com/url_to_go_to/page/%1? [R=301,L]

Notice the ? sign at the end of the new URL for clearing the query string.

Hope someone will find this article useful. Enjoy ;)

 

2 Comments for “Apache redirect dynamic urls”

  1. zum Says:

    Excellent article, thank you very much!

  2. claude Says:

    Your wellcome.
    You all can post your experience on this website and into the forums on it. That way more will beneffit ;)

Post a comment

Name (required)

Mail (will not be published) (required)

Website

*
To prove you're a person (not a spam script), type the security text shown in the picture. Click here to regenerate some new text.
Click to hear an audio file of the anti-spam word