Forum

Redirect query string to url using .htaccess

1

I am trying to redirect this url:

https://www.example.com/?category=1&page=1
to this url:

https://www.example.com/?category=1
I have 12 categories, can i redirect all with one code? for example i have

https://www.example.com/?category=2&page=1 => https://www.example.com/?category=2
https://www.example.com/?category=3&page=1 => https://www.example.com/?category=3
.
.
.
my code doesn't work:

RewriteEngine On
# RewriteCond %{REQUEST_URI} ^\/index\.php$
RewriteCond %{QUERY_STRING} ^category=([0-9]*)&page=1
RewriteRule ^(.*)category=([0-9]*)&page=1$ https://www.example.com/?category=([0-9]*)%1 [R=302,L]
I have already redirected all index.php with this code and works:

RewriteEngine on
RewriteCond %{THE_REQUEST} ^.*/index\.php
RewriteRule ^(.*)index.php$ /$1 [R=301,L]

Reply to this topic Share on my timeline

1 Replies

Avatar

Code Dev·

RewriteCond %{QUERY_STRING} ^category=([0-9]*)&page=1
RewriteRule ^(.*)category=([0-9]*)&page=1$ https://www.example.com/?category=([0-9]*)%1 [R=302,L]
The RewriteRule pattern (first argument) matches against the URL-path only, not the query string. You are already matching the query string in the RewriteCond directive, so there's no need to do this twice anyway.

If there is no URL-path (ie. all requests target the document root) as per your examples then you can simplify the pattern and there is no need to capture the URL-path.

Including the regex ([0-9]*) in the substitution string (2nd argument) makes no sense. This is an "oridinary" string, not a regex.

Try the following instead:

RewriteCond %{QUERY_STRING} ^(category=d{1,2})&page=1$
RewriteRule ^$ /?%1 [R=302,L]
Instead of capturing just the category value, we might as well capture the complete name/value pair and avoid repetition.

d is a shorthand character class and is the same as [0-9]. I've also changed this so that it matches just 1 or 2 digits (since you say you only have 12 categories). Using the * quantifier would allow an empty category parameter.

Note that this matches the document root only, as per your examples. ie. it won't match example.com/foo?category=1&page1. And only URLs that contain page=1 as a 2nd URL param.

You don't need to include the full absolute URL in the target, unless you want to include this as part of your canonical redirect.