Search code examples
.htaccess

how to Remove Sub directory name from URL with htaccess?


My URL was

http://demo.example.com/parentFolder/

but i have to redirect it to child folder, URL as

http://demo.example.com/parentFolder/ChildFolder/

i have redirect it in htaccess as

<IfModule mod_rewrite.c>

       RewriteEngine On
       RewriteCond %{HTTP_HOST} ^(www.)?demo.example.com/parentFolder$
       RewriteCond %{REQUEST_URI} !^/ChildFolder/


       RewriteCond %{REQUEST_FILENAME} !-f
       RewriteCond %{REQUEST_FILENAME} !-d

       RewriteRule ^(.*)$ /ChildFolder/$1

       #RewriteCond %{HTTP_HOST} ^(www.)?demo.example.com/parentFolder$
       RewriteRule ^(/)?$ ChildFolder/ [L]

</IfModule>

but didn't remove sub folder(ChildFolder) from URL. i want to access childFolder after redirect but want to hide childFolder from URL.


Solution

  • You can use these rule in parentFolder/.htaccess:

    RewriteEngine On
    
    # remove ChildFolder from URL show in browser
    RewriteCond %{THE_REQUEST} \s/+(parentFolder)/ChildFolder/(\S*)\s [NC]
    RewriteRule ^ /%1/%2 [R=301,NE,L]
    
    # add ChildFolder internally
    
    RewriteRule ^$ ChildFolder/ [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(?!ChildFolder/).*$ ChildFolder/$0 [L,NC]