John John - 13 days ago 11
Apache Configuration Question

.htaccess remove subdirectory from URL but include sub-subdirectory

I have a local set up like this:

local.com/test/folder1/

How can I remove the 'test' directory from the URL but still include 'folder1' through .htaccess? like this:

local.com/folder1/

any help would be appreciated.

Answer

You can use this rule in site root .htaccess:

RewriteEngine On

# add a trailing slash if test/$1 is a directory
RewriteCond %{DOCUMENT_ROOT}/test/$1 -d
RewriteRule ^(.*[^/])$ %{REQUEST_URI}/ [L,R=301,NE]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(?!test/)(.*)$ test/$1 [L,NC]

(?!test/) is negative lookahead to skip rewrite when request is already starting with /test/

Comments