Search code examples
regex.htaccesshttp-redirectmod-rewritemod-alias

RedirectMatch: redirects to wrong URL


I switched a Shop-CMS and put a lot of old URL into the .htaccess to redirect old products to their new location.

But some redirects are wrong:

RedirectMatch 301 ^/products/catxy/313? https://www.example.com/products/catxy/product-1/
RedirectMatch 301 ^/products/catxy/314? https://www.example.com/products/catxy/product-2/
RedirectMatch 301 ^/products/catxy/319? https://www.example.com/products/catxy/product-3/

When I go to example.com/products/catxy/319 I get redirected to product-1 and not to product-3

As I understand the regex above it means starting with /products/catxy/319[MAYBEMORE] -> redirect to product-3

I can't write ^/products/catxy/319$ because there are a lot of different endings for 319 (all variations of that product id).

I don't know either if it would be better to use mod_rewrite in my situation.


Solution

  • Problem is presence of ? in the end of pattern: ^/products/catxy/313?, which is making last digit optional so your first rule matches anything that starts with:

    /products/catxy/313
    

    or

    products/catxy/31
    

    You probably means to keep trailing slash optional and have your rules like this:

    RedirectMatch 301 ^/products/catxy/313(?:/.*)?$ https://www.example.com/products/catxy/product-1/
    RedirectMatch 301 ^/products/catxy/314(?:/.*)?$ https://www.example.com/products/catxy/product-2/
    RedirectMatch 301 ^/products/catxy/319(?:/.*)?$ https://www.example.com/products/catxy/product-3/
    

    Remember to clear your browser cache before testing the changes.