Reputation: 14984
On my website, when somebody requests a directory, I want it to remove the '/' and add '.html' (minus the quotes, of course).
Example:
If someone goes to domain.com/directory/
it should redirect to domain.com/directory.html/
and the same should stand for: domain.com/another-directory/
should redirect to domain.com/another-directory.html
.
I would like to place a line (or two) of code to my htaccess
file that will make any directory (URL ending with /
) redirect to URL.html
(removing the /
of course).
I would also like it to visually redirect, so the user will actually see it change to .html
.
I'm quite a novice web programmer, and any help is greatly appreciated.
Note: I did use Redirect /directory /directory.html
and that worked, but that requires a lot of extra coding, and I would much prefer one simple statement to cover all directories.
Upvotes: 0
Views: 1435
Reputation: 143896
This is going to be a bit difficult with htaccess, I assume you want to do the following:
First one is straightforward:
# check to make sure the request isn't actually for an html file
RewriteCond %{THE_REQUEST} !^([A-Z]{3,9})\ /(.+)\.html\ HTTP
# check to make sure the request is for a directory that exists
RewriteCond %{REQUEST_FILENAME} -d
# rewrite the directory to
RewriteRule ^(.+)/$ /$1.html [R]
Second part is tricky
# check to make sure the request IS for an html file
RewriteCond %{THE_REQUEST} ^([A-Z]{3,9})\ /(.+)\.html\ HTTP
# See if the directory exists if you strip off the .html
RewriteCond %{DOCUMENT_ROOT}/%2 -d
# Check for an internal rewrite token that we add
RewriteCond %{QUERY_STRING} !r=n
# if no token, rewrite and add token (so that directories with index.html won't get looped)
RewriteRule ^(.+)\.html /$1/?r=n [L,QSA]
However, if what you just have is a bunch of files called directory.html
, directory2.html
, directory3.html
, etc. and you want to make it so when someone enters http://domain.com/directory2/ into their address bar they get served the contents of directory2.html
, it will be much simpler:
# check to make sure the request isn't actually for an html file
RewriteCond %{THE_REQUEST} !^([A-Z]{3,9})\ /(.+)\.html\ HTTP
# check to see if the html file exists (need to do this to strip off the trailing /)
RewriteCond %{REQUEST_URI} ^/(.+)/$
RewriteCond %{DOCUMENT_ROOT}/%1.html -f
# rewrite
RewriteRule ^(.+)/$ /$1.html [L]
Upvotes: 1