mikejohnvino mikejohnvino - 2 months ago 8
PHP Question

301 redirect not working properly with htaccess

http://www.domain.com/thanks.php?orderid=MTI0NjAx

Above url should redirect to
http://www.domain.com/order-confirmation/MTI0NjAx

But now its redirecting to below url like...
http://www.domain.com/order-confirmation/MTI0NjAx?orderid=MTI0NjAx

I'm using this below code, but not working properly...

RewriteCond %{THE_REQUEST} /thanks\.php\?orderid=([^&\s]+) [NC]
RewriteRule ^ /order-confirmation/%1 [NC,R=301,L]
RewriteRule ^order-confirmation/([^/]+)$ /thanks\.php\?orderid=$1 [NC,L]


anyone help me, how do I do this?

Answer

You need to use ? in target URL to strip off previous query string:

RewriteCond %{THE_REQUEST} /thanks\.php\?orderid=([^&\s]+) [NC]
RewriteRule ^ /order-confirmation/%1? [R=301,L]

RewriteRule ^order-confirmation/([^/]+)$ /thanks\.php\?orderid=$1 [NC,L,QSA]

Starting with Apache 2.4 you can also use QSD (Query String Discard) flag to trip off previous query string.