Remove double URL encoding on URL

apache-2.4mod-aliasmod-rewriteurl

I have a third-party shopping cart set up on my server using PayPal for payments. When a user completes a transaction they are redirected to the URL https://example.com/?target=payment%255freturn&txn_id_name=txnId.... The correct URL should include target=payment_return or target=payment%5freturn. These URLs work correctly, presenting the customer with their invoice, but the URL that PayPal redirects to is URL encoded twice and so gives the customer a 404 error.

I cannot change the logic of the application to accept the twice-escaped URL so I have been trying to set up a redirect to correct it. I've tried numerous variants on the following, using mod_alias or mod_rewrite:

RedirectMatch permanent (?i)^/\?target=payment%255freturn(.*) /target=payment_return$1

RewriteRule ^/\?target=payment%255freturn(.*) /target=payment_return$1 [NE]

I've tried variations of %255f, %5f, and _, and I've tried with and without the NE flag.

How can I have the user successfully redirected to the correct URL?

Best Answer

You could try utilizing a scripting language to fix this. For example, you could do something like the following:

RewriteEngine on
RewriteCond %{REQUEST_URI} ^/\?target=payment%255freturn.*
RewriteRule (.*) unescaper.php?url=$1 [L]

Then in unescaper.php do something like:

<?php
$decoded_url = rawurldecode($_GET['url']);
header('Location: ' . $decoded_url);
exit;

Disclaimer: I didn't test this .htaccess or code, but it should get you very close. If rawurldecode isn't right for your case (but I think it is), check out urldecode.