I have my URL address like this www.example.com/subfolder/index1
and I want to achieve the following result www.example.com/index1
(see below I only have 2 subfolders, I have to do the same for both).
The folder that I have in my project are the following:
index.html (main page)
subfolder1 -> index1.html
subfolder2 -> index2.html
I have the following code in my htaccess file so far:
index.html
RewriteEngine on
RewriteCond %{THE_REQUEST} /([^.] )\.html [NC]
RewriteRule ^ /%1 [NC,L,R]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]
CodePudding user response:
By having two "hidden" subdirectories (/subfolder1
and /subfolder2
) you've created an ambiguity. eg. Where should a request for /foo
be rewritten to? Should it be /subfolder1/foo.html
or /subfolder2/foo.html
? The only way to determine this is to first check if the file exists in /subfolder1
, otherwise rewrite to /subfolder2
.
You also appear to be using .html
extensionless URLs. And you appear to be referencing files outside of these two subfolders.
Try something like the following:
DirectoryIndex index.html
RewriteEngine On
# Redirect any direct requests for "/subfolder1" or "/subfolder2" back to the root
# - Except for "assets"
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{REQUEST_URI} !^/[^/] /assets/
RewriteRule ^(?:subfolder1|subfolder2)(?:$|/(.*)) /$1 [R=301,L]
# Remove "index.html" entirely if requested
RewriteRule (^|. /)index\.html$ /$1 [R=301,L]
# Remove ".html" extension if requested directly
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^([^.] )\.html$ /$1 [R=301,L]
# Rewrite requests to subfolder1 if ".html" file exists in that subdir
RewriteCond %{DOCUMENT_ROOT}/subfolder1/$1.html -f
RewriteRule ^([^.] )$ subfolder1/$1.html [L]
# Rewrite requests to subfolder2 if ".html" file exists in that subdir
RewriteCond %{DOCUMENT_ROOT}/subfolder2/$1.html -f
RewriteRule ^([^.] )$ subfolder2/$1.html [L]
# Otherwise append ".html" if the file exists
# - Only required if you are serving other HTML files outside of the subfolders
# - (Excluding "/index.html" in the document root)
RewriteCond %{DOCUMENT_ROOT}/$1.html -f
RewriteRule ^([^.] )$ $1.html [L]
A few assumptions:
- your static resources (images, CSS, JS, etc) are requested directly and include
/subfolder1
or/subfolder2
in the URL. Otherwise it becomes problematic to resolve all ambiguities between/subfolder1
and/subfolder2
. However, this does mean the/subfolder1
(or/subfolder2
) is not truly "hidden". - Your extensionless URLs do not contain a dot (which otherwise delimits the file extension).
NB: Test with 302 (temporary) redirects to avoid potential caching issues.