Handle $_GET requests with Clean URLs

2019-01-20 20:02发布

问题:

I am have a clear URL based system so the categories will be shown like this

http://www.mysite.com/category/23/cat-name

Inside the categories page I have some sorting and pages options such as sorting by latests and lower price. Also, I have a pages navigation system

The problem is when the request is happening inside the page the $_GET[] doesn't show the variables I need. However it shows in the URL as

http://www.mysite.com/category/23/cat-name?page=3

The $_GET variable only shows the id of the category which is in our case now = 23 and ignored the page number which is in the url.

.htaccess content

RewriteEngine On
RewriteRule ^category/([0-9]+)/[a-z][-a-z0-9]*$ cat.php?id=$1

回答1:

You need to include the QSA flag at the end of your rule. This appends any existing query string to the one that you're constructing in the rule itself:

RewriteEngine On
RewriteRule ^category/([0-9]+)/[a-z][-a-z0-9]*$ cat.php?id=$1 [L,QSA]

So the rewritten URI should end up being: /cat.php?id=23&page=3



回答2:

Add QSA(query string append) at the end of your rewrite rule.

RewriteEngine On
RewriteRule ^category/([0-9]+)/[a-z][-a-z0-9]*$ cat.php?id=$1 [L,QSA]

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.

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.