22 March 2007

Rerouting old style PHP query string urls to a Rails app

I've re-written an old php application in Ruby on Rails. In anticipation of flipping the switch from the old site to the new one, it would be nice to re-route requests for the old php pages to their new home.

The old page url would look something like this:

/page.php?pageid=mypage

with the new equivalent being this:

/page/mypage

I wasn't sure if the best place to handle the rerouting would be the rails routes.rb file, or using mod_rewrite in the .htaccess file.

I didn't find a way to do it using routes.rb, so here's the solution I came up with to make it work using .htaccess:

RewriteCond %{QUERY_STRING} ^pageid=(.*)$
RewriteRule ^page\.php /page/%1? [R=301,L]

I added the two lines after the original "RewriteRule ^$ index.html [QSA]" line.

I found all kinds of information about doing the opposite - i.e. rewriting /page/pageid/mypage to redirect to page.php?pageid=mypage. I had to sift through all that to find what I needed.

1 comment:

harold said...

Funny - this worked as shown in the post on one server, but when moved to another it was being ignored until I added the beginning slash "/" on the RewriteRule line like this:

RewriteRule ^/page\.php /page/%1? [R=301,L]

I pulled my hair out on this one for a while...