Efoskhi
Efoskhi

Reputation: 61

How to rewrite URL GET parameters

I have a URL

https://example.com/cart?prdid=223 I want to redirect it to

https://example.com/cart/223

using .htaccess

i've tried to use

RewriteEngine on
RewriteCond %{QUERY_STRING} (?:^|&)prdid=(.*)$
RewriteRule ^cart/(.*)$ /cart/$1?prdid=%1 [L,R]

But it does not work.

Upvotes: 0

Views: 175

Answers (1)

IMSoP
IMSoP

Reputation: 97678

Rewrite rules have the pattern to match first, then the result you want.

The pattern you need to match is the current URL, which just ends "/cart", with no extra slash or word on the end of it, so instead of cart/(.*)$ you just want cart$

Then the result you want has the ID directly in the URL, not in the query string, and there's nothing for $1 to refer to, only %1 from the RewriteCond line. So instead of /cart/$1?prdid=%1 you just want /cart/%1

Once you've fixed that, the browser will redirect to the new URL. To actually make that URL work, you'll probably need a second rule, without the R flag, to tell Apache what to do when it sees the "pretty" URL. That one will have cart/(.*)$ as the pattern to match, but no condition on the query string, and $1 in the result part, not %1

Upvotes: 1

Related Questions