For a website I just relaunched, I would like a htaccess redirect catching all non-existing subpages under /blog/
to just point to /blog/
and not a 404 (so /blog/old-page/
would just redirect to /blog/
). It's important however that the still existing subpages (such as /blog/new-page/
) aren't redirected. It's also best if this can be in the root htaccess file (not in the subfolder). I feel like I've tried everything, but can't find a solution for this without making redirects for every single old subpage (there are >100)!
I hope someone can help.
CodePudding user response:
If all your old page URLs were of the form /blog/<old-page>/
and previously mapped to physical directories (from which a DirectoryIndex
document was served) then you can do something like the following using mod_rewrite at the top of your root .htaccess
file:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(blog/)[^/] /$ /$1 [R=301,L]
$1
in the substitution string is a backreference to the first capturing group in the RewriteRule
pattern, ie. “blog/“. This simply saves repetition.
Aside: Just to repeat the concern expressed in comments. With regards to SEO and users, this is likely worse than a custom 404 response that explains the absent page(s). Search engines will likely see this (a many to one redirect) as a soft-404 anyway and users are more likely to just be "confused" (and bounce) when they see different content to what they are expecting. There really is no substitute for "old" to "new" (one-to-one) 301 redirects.