Passing dynamic variables in htaccess / php

I have a website that is dynamic and the information (area / category / subcategory) goes through htaccess for nice urls. For example, when a user plunges into categories, he flows as follows:

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

I was wondering if there is a way to extend this since in htaccess so that I can pass more elements and capture the variable using php, i.e.

 /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 that the first line refers to /products/hard-drives/hard-drives-sas , the second refers to /products/hard-drives , and then just the /parts page

Hope this makes sense!

Thanks.

+6
source share
2 answers

Use the 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 a pluggable URI contains a query string, the default behavior of the RewriteRule is to discard the existing query string and replace it with a new one. Use the [QSA] flag of the query string to be combined.

Consider the following rule:

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

With the flag [QSA] will the request for / pages / 123 be displayed? one = two on /page.php?page=123&one=two. Without the [QSA] flag, the 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

+13
source

I really believe that editing your .htaccess on the server to adapt this concept of routing will be a real pain. I would recommend you take a look at the PHP framework like CodeIgniter, CakePHP, etc. All of them have already prepared the necessary routing mechanism. And this is pretty easy to understand. Editing .htaccess will have an obvious flaw: how many rules are you going to add when you have big requirements for such routing requirements.

0
source

All Articles