Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass dynamic variables in htaccess / php

Tags:

php

.htaccess

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.

like image 489
David Avatar asked Jan 17 '13 16:01

David


1 Answers

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

like image 141
Peter Avatar answered Sep 21 '22 13:09

Peter