rewriting query string with optional parameters

Discuss practical ways rearrange URLs using mod_rewrite.

rewriting query string with optional parameters

Postby thetafferboy » Fri Jun 19, 2009 2:23 pm

Hey all.

Firstly, apologies as I imagine this has been answered before, but I have searched and had a look through the forum and can't find the answer.

I'm rewriting some URLs for an e-commerce site with a category, sub-category and product id.

So for instance, the php file that handles:

mydomain.com/product.php?cat=MYCAT&sub=MYSUBCAT&prod=MYPROD

comes from:

mydomain.com/category/subcat/product

No problems there, but I need to make the 2nd/3rd (subcat/product) optional. I know you can use the ? with brackets to do this, but I get server errors when I try.

My working mod_rewrite is:

RewriteRule ^/?([a-zA-Z_\-]+)/([a-zA-Z_\-]+)/([a-zA-Z_\-]+)$ product.php?cat=$1&sub=$2&prod=$3

How can I write this so the last 2 are optional?

Thanks in advance.
Mark
thetafferboy
 
Posts: 1
Joined: Fri Jun 19, 2009 2:18 pm

Postby richardk » Sat Jun 20, 2009 8:55 am

Code: Select all
Options +FollowSymLinks

RewriteEngine On

RewriteRule ^([-a-z_]+)/?$                       /product.php?cat=$1                [NC,QSA,L]
RewriteRule ^([-a-z_]+)/([-a-z_]+)/?$            /product.php?cat=$1&sub=$2         [NC,QSA,L]
RewriteRule ^([-a-z_]+)/([-a-z_]+)/([-a-z_]+)/?$ /product.php?cat=$1&sub=$2&prod=$3 [NC,QSA,L]


Or
Code: Select all
Options +FollowSymLinks

RewriteEngine On

RewriteRule ^([-a-z_]+)(?:/([-a-z_]+)(?:/([-a-z_]+))?)?/?$ /product.php?cat=$1&sub=$2&prod=$3 [NC,QSA,L]
richardk
 
Posts: 8800
Joined: Wed Dec 21, 2005 7:50 am


Return to Friendly URLs with Mod_Rewrite

Who is online

Users browsing this forum: No registered users and 25 guests

cron