Home > Back-end >  RedirectMatch without last part of URL
RedirectMatch without last part of URL

Time:04-05

I have this RedirecMatch

RedirectMatch 301 ^/en/products/(.*)/(.*)/(.*)$ https://www.example.com/en/collections/$2/

If I visit

https://www.example.com/en/products/sofas/greyson/greyson-sofa

I'm redirected to

https://www.example.com/en/collections/greyson/greyson-sofa

What I want is

https://www.example.com/en/collections/greyson/

How do I accomplish this?

CodePudding user response:

There's nothing obvious in what you have posted that would produce the specific output you are seeing, however, there are other errors in the directives and you may be seeing a cached response. 301s are cached persistently by the browser, so any errors are also cached.

The Redirect directive is prefix-matching and everything after the match is copied onto the end of the target URL. So, the redirect you are seeing would be produced by a directive something like this:

Redirect 301 /en/products/sofas/greyson https://www.example.com/en/collections/sofas/greyson

When you request /en/products/sofas/greyson/greyson-sofa, the part after the match, ie. /greyson-sofa, is copied onto the end of the target URL to produce /en/collections/sofas/greyson/greyson-sofa

You can resolve most of these issues by reordering your rules (but also watch the trailing slashes). You need to have the most specific redirects first. RedirectMatch before Redirect. For example, take the following two redirects:

Redirect 301 /en/products/accessories https://www.example.com/en/products/complements/
Redirect 301 /en/products/accessories/bush/ https://www.example.com/en/collections/bush-on/

Since the Redirect directive is prefix-matching, a request for /en/products/accessories/bush/ will actually be caught by the first rule, not the second and end up redirecting to /en/products/complements//bush-on/ - note the erroneous double-slash (since you have a mismatch of trailing slashes on the source and target URLs.)

You need to reverse these two rules. (But also watch the trailing slash.)

The same applies to the Redirect directives that follow. You also have some duplication, ie. You have two rules for /en/products/chairs-and-bar-stools/piper/?

  • Related