Home > Blockchain >  301 redirect not working for subpage, not found error
301 redirect not working for subpage, not found error

Time:02-18

Hi I have some URL like this

/dvr-model/110
/dvr-model/110/spider
/dvr-model/110/spencer
/dvr-model/110/whale/47

I am doing like this

 Redirect 301 /dvr-model/110 https://newurl
 Redirect 301 /dvr-model/110/spider https://newurl
 Redirect 301 /dvr-model/110/spencer https://newurl
 Redirect 301 /dvr-model/110/whale/47 https://newurl

Now first redirect is working fine but all other URLs are giving not found error. What am I doing wrong here?

CodePudding user response:

but all other URLs are giving not found error.

Specifically, if you request /dvr-model/110/spider then the first rule will redirect the request to https://newurl/spider (which is presumably a 404).

The Redirect directive is prefix-matching and everything after the match is copied to the end of the target URL. So in the above example /spider is appended to the end of the target URL.

You need to reverse your rules so the most specific rules are first, or at least just have the first (generic) rule last.

For example:

Redirect 301 /dvr-model/110/spider https://newurl
Redirect 301 /dvr-model/110/spencer https://newurl
Redirect 301 /dvr-model/110/whale/47 https://newurl
Redirect 301 /dvr-model/110 https://newurl

Or use RedirectMatch, that uses a regex rather than simple prefix-matching, to match the exact URLs, for example:

RedirectMatch 301 ^/dvr-model/110$ https://newurl
RedirectMatch 301 ^/dvr-model/110/spider$ https://newurl
RedirectMatch 301 ^/dvr-model/110/spencer$ https://newurl
RedirectMatch 301 ^/dvr-model/110/whale/47$ https://newurl

Which can be reduced to a single rule using regex alternation:

RedirectMatch 301 ^/dvr-model/110(/spider|/spencer|/whale/47)?$ https://newurl

You will need to clear your browser cache before testing and test with 302 (temporary) redirects first to avoid potential caching issues.

Reference:

  • Related