royjr royjr - 6 months ago 9
PHP Question

.htaccess url rewrite challenge with query

Have a little challenge. I'm have trouble adding another "filter" to my current rewrite code. I want to add another rewrite that captures the query string at the end of the url (if supplied)

Example..

example.com/search/?sort=newest --> example.com/search.php?sort=newest
example.com/search/first?sort=newest --> example.com/search.php?a=first&sort=newest
example.com/search/first/second?sort=newest --> example.com/search.php?a=first&b=second&sort=newest
example.com/search/first/second/third?sort=newest --> example.com/search.php?a=first&b=second&c=third&sort=newest


This is my current code.

# search without filters
RewriteRule ^search?$ search/ [NC,L]

# search with one filter
RewriteRule ^search/([A-Za-z0-9-+]+)?$ search.php?a=$1 [NC,L]

# search with two filters
RewriteRule ^search/([A-Za-z0-9-]+)/([A-Za-z0-9-+]+)?$ search.php?a=$1&b=$2 [NC,L]

# search with three filters
RewriteRule ^search/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-+]+)?$ search.php?a=$1&b=$2&c=$3 [NC,L]

Answer

To keep an existing query string in a RewriteRule, you don't need to do anything.

But if you add a query string yourself in the substitution part, you need to use the QSA flag to append the previous query string

RewriteRule ^search/([A-Za-z0-9-+]+)?$ search.php?a=$1 [NC,L,QSA]
Comments