I am trying to get the variable from my url but having problems.
the default URL is http://localhost/category.php?category_slug=gaming
With my htaccsess file
RewriteRule ^category/([\w\d-]+)$ /category.php?category_slug=$1 [L]
RewriteCond %{QUERY_STRING} category_slug=([\w\d-]+)
RewriteRule ^category$ %1 [R,L]
I get my desired URL http://localhost/category/gaming
but now I am needing to get the page variable from the url http://localhost/category/gaming?page=2
in category.php i have $page=$_GET['page']
;
but when I echo it out i get Warning: Undefined array key "page" in F:\Server\htdocs\category.php on line 5
The closest i can get is with the following code
RewriteRule ^category/([\w\d-]+)$ /category.php?category_slug=$1&page=$2 [L]
RewriteCond %{QUERY_STRING} category_slug=([\w\d-]+)
RewriteRule ^category$ %1 [R,L]
I get no errors but the data isnt showing
The desired URL would be either
http://localhost/category/gaming?page=2
or http://localhost/category/gaming/page2/
im pretty sure my lack of knowledge of editing my htaccsess file is to blame. and need someone to point me in the right direction please
RewriteRule ^category/([\w\d-]+)$ /category.php?category_slug=$1 [L]
You need to add the QSA
(Query String Append) flag to the first rule that rewrites the request. This appends/merges the query string on the request (ie. page=2
) with the query string you are including in the substitution string (ie. category_slug
), otherwise the query string in the substitution replaces the query string on the request.
(If, however, you are not including a query string in the substitution string then the original query string on the request is passed through by default - no need for the QSA
flag in this case.)
Minor point, but the \w
shorthand class already includes digits, so the \d
is superfluous.
You should also make sure that MultiViews is disabled, otherwise all query string parameters will be lost.
For example:
Options -MultiViews
RewriteRule ^category/([\w-]+)$ /category.php?category_slug=$1 [QSA,L]
This then handles both /category/gaming
and /category/gaming?page=2
.
Aside:
RewriteCond %{QUERY_STRING} category_slug=([\w\d-]+) RewriteRule ^category$ %1 [R,L]
Your second rule isn't actually doing anything, unless this is related to something else. This would likely result in a malformed redirect if it did anything at all?
This rule would redirect a URL of the form /category?category_slug=gaming
to gaming
(only) - which is dependent on you having a RewriteBase
defined. Is that the intention?