Search code examples
.htaccesshttp-redirecturl-rewriting

Redirect (rewrite?) subfolders to parent folder


I've moved all my PDF files from several subfolders to the parent folder /downloads/ Examples old situation:

https://www.example.com/downloads/2011/subfolder2/subfolder3/file1.pdf
https://www.example.com/downloads/2011/subfolder4/subfolder5/subfolder6/file2.pdf
https://www.example.com/downloads/2011/subfolder7/file3.pdf
https://www.example.com/downloads/2011/subfolder7/file4.pdf

So it was all about PDF files in different subfolders in /downloads/2011/

And now it's like this (there are many more files):

https://www.example.com/downloads/file1.pdf
https://www.example.com/downloads/file2.pdf
https://www.example.com/downloads/file3.pdf
https://www.example.com/downloads/file4.pdf

I'd like to redirect the old links in the search engines to the new. So in fact all subfolders (except downloads) should be removed from the old url's or all old links to all PDF's on the site, wherever they were, should be redirected to the downloads folders.

How should I do any of these possibilities with .htaccess?


Solution

  • RewriteRule ^downloads\/.+\/(.+)$ downloads/$1 [R=301]
    

    That should do the trick already.

    There appears to be no need to be more specific with the first .+ match, or use character classes that exclude the slash; the greediness of regular expressions works in our favor here.