Redirect anything within /attachments/ directory up one level but also removing anything after /attachments/

.htaccessredirect

WordPress creates an attachment page for any images uploaded through the post editor and "attached" to that post. After migrating a site, those attachment pages no longer exist, and we now have around 1000 links pointed at 404's.

So, I was looking to find a way to do a redirect for any url that has /attachement/ in it's string and then push that url back up one level (which happens to be the post page). so for instance:

http://mysite.com/2012/news/blog-post-title/attachment/image-page/ (which doesnt exist) will go to
http://mysite.com/2012/news/blog-post-title/ (which does exist).

Along with redirecting up one level, I also need to remove anything after /attachment/ (in this case the "image-page."

Any suggestions?

Thanks in advance

Best Answer

This sounds like an extremely simple rewrite; unless there's something missing, you can use:

RewriteRule ^(.*)/attachment/?.*$ $1/

So some test cases:

/2012/news/blog-post-title/attachment/image-page/ -> /2012/news/blog-post-title/
/2012/news/blog-post-title/attachment             -> /2012/news/blog-post-title/
/2012/news/blog-post-title/attachments            -> N/A

Hope this helps!