Search code examples
.htaccesshttp-redirectsubdirectoryfriendly-url

how to redirect all files in a subfolder to root directory with htaccess


i have a directory like www.example.com/comments/a/word1.html I removed comments/a/ section and .html with htaccess from link. Under the a folder i have lots of files like word1.html, word2.html , word3.html, and i want to redirect all of these files like this: www.example.com/word1 www.example.com/word2 www.example.com/word3

I am using this .htaccess code:

RewriteEngine on
RewriteRule ^/?comments/a/(.*)(/|\.html)?$ /$1 [R=301,L] 
RequestCond %{DOCUMENT_ROOT}/comments/a%{REQUEST_URI}.html -f 
RewriteRule ^/?(.*)/? /comments/a/$1.html [END] 

but i got the error "404 page not found, The resource requested could not be found on this server!". What can i do in this situation? Is there any way to redirect www.example.com/comments/a/word1.html word2-3-4 etc. also to www.example.com/word1


Solution

  • As a result of my researchs i found a solution like this :

    ##Rewrite non /comments/a/ links internally start##
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{DOCUMENT_ROOT}/comments/a/$1.html -f
    RewriteRule ^/?([^.?]+)$/?$ comments/a/$1.html [L,NC]
    ##Rewrite non /comments/a/ links internally end##
    

    This code works like a charm for me.