Alacrify Ltd

Using .htaccess to Redirect Pages with $_GET Variables to Friendly URLs

Published on: 4th February 2011
By Alacrify



Using .htaccess to Redirect Pages with $_GET Variables to Friendly URLs

As part of the recent changes to the OSE Directory website we changed the url structure that was used for the pages.

The pages were set up with a number of $_GET variables that then were used to find records or search the site. They were in this kind of format:

company.php?type=health&company_id=12

We needed to find a way to break this up and redirect it to our new friendly url version, which, in its simplest form is:

/1-5-12/

[where health is denoted by 1 and company by 5, and the company id is retained]

(NB we're using canonical links on the pages, so the urls found by Google et al will actually include the company name and so on.)

Using .htaccess to Rewrite to Friendly URLs

We wanted to use .htaccess to handle this transformation rather than putting a PHP/header redirect into the "old" files so that the new pages would be properly indexed in their own right. We spent several hours looking for solutions to this problem, and trying out various approaches.

This is the solution we ended up with:

RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} type=health
RewriteCond %{QUERY_STRING} company_id=([0-9]+)
RewriteRule company.php(.*) /1-5-%1/? [R=301,L]

There are several of these for each of the permutations of $_GET variables. The [R=301] means that the visitor's url is updated with the new Friendly URL.

To explain it a bit:

  • The first RewriteCond statement checks for the presence of the type=health variable.
  • Then the second RewriteCond looks for a match on company_id and grabs the actual value of this variable.
  • The final RewriteRule translates any company.php pages that match this pattern to the new friendly url.

Job done.

You can see it in action here:
www.osedirectory.com/company.php?type=health&company_id=317