Search code examples
regexapache.htaccessmod-rewritetrailing

htaccess redirect url with trailing %20


We use pretty urls on our site. I had an external technician add back links some years ago. He did a great job, but in one case, he consistently added a link with a trailing space character.

https://www.example.com/item/item/%20

This has been indexed as %20 and I can see on my back link reports that there are 87 sites that point to the URL with %20 at the end.

If I can redirect this, then my page /item/item/ would gain 87 back links.

We use rewrite rules, and I have tried every solution here on stack overflow, but none has worked. Some non working solutions are:

RewriteEngine on
RewriteRule ^(.*[^\ ])\ +$ /$1

RedirectRule (.*)\s$ $1 [R=301]

RewriteRule ^(.*/|)[\s%20]+(.+)$ $1$2 

I have tried a redirect 301 but these don't work either.

redirect 301 /item/item/%20 /item/item/

redirect 301 /item/item/+ /item/item/

Some things that helps - this is not a site wide pattern. It is just one particular URL that got propagated out into the world incorrectly. And it is not a space anywhere in the string - it is always at the end.

Thanks.

It would also work fine for me to convert the trailing %20 to a known character like a - because I could redirect it /item/item/- to item/item/


Solution

  • You can use this rule as your topmost rule just below RewriteEngine On line:

    RewriteEngine On
    
    RewriteRule ^(.*)(?:\s|\x20)+$ /$1 [L,NE,R=301]