David
David

Reputation: 369

Pass dynamic variables in htaccess / php

I have a site created which is dynamic and the information (area / category / subcategory) passes through htaccess for nice URLs. For example, as the user dives into the categories it flows as follows:

/parts/hard-drives

/parts/hard-drives/hard-drives-sas

I wondered if there was a way to extend this from then on in htaccess so I can pass more items and grab the variable with php, ie:

/parts/hard-drives/hard-drives-sas/?manufacturer=dell&price=20

My current lines for the htaccess file are as follows:

RewriteRule ^parts/([^/\.]+)/([^/\.]+)/?$ parts.php?p=$1&f=$2 [L]
RewriteRule ^parts/([^/\.]+)/?$ parts.php?p=$1 [L]
RewriteRule ^parts parts.php [L]

You will see the first line relates to /products/hard-drives/hard-drives-sas the second relates to /products/hard-drives and then simply a parts page /parts

Hopefully that makes sense!

Thanks.

Upvotes: 8

Views: 9097

Answers (2)

Cayter Goh
Cayter Goh

Reputation: 11

I do believe that by editing your .htaccess on the server to adapt this routing concept will be a real pain. I would recommend that you should take a look at the PHP framework like CodeIgniter, CakePHP and etc. They all have already prepared the routing mechanism that you wanted. And it's quite easy to understand. By editing .htaccess, there'll be an obvious disadvantage which is how many rules you are going to add when you have large demands of this kind of routing requirements.

Upvotes: 0

Peter
Peter

Reputation: 16943

Use QSA flag to pass GET variables:

RewriteRule ^parts/([^/\.]+)/([^/\.]+)/?$ parts.php?p=$1&f=$2 [L,QSA]
RewriteRule ^parts/([^/\.]+)/?$ parts.php?p=$1 [L,QSA]
RewriteRule ^parts parts.php [L,QSA]

Docs:

When the replacement URI contains a query string, the default behavior of RewriteRule is to discard the existing query string, and replace it with the newly generated one. Using the [QSA] flag causes the query strings to be combined.

Consider the following rule:

RewriteRule /pages/(.+) /page.php?page=$1 [QSA]

With the [QSA] flag, a request for /pages/123?one=two will be mapped to /page.php?page=123&one=two. Without the [QSA] flag, that same request will be mapped to /page.php?page=123 - that is, the existing query string will be discarded.

http://httpd.apache.org/docs/2.2/rewrite/flags.html#flag_qsa

Upvotes: 14

Related Questions