regexapache.htaccesshttp-redirecttrailing-slash

Htaccess – remove html extension + add trailing slash + find index inside subfolder (combined)


I've been struggling with this question for a week now.

My website root is something like this:

index.html
page.html
subfolder/index.html
subfolder/page.html

I've read tons of posts to do these 3 things. I can actually do them separately but I can't figure how to do them combined!

  1. Remove the .html extension
  2. Automatically look for index.html inside a subfolder
  3. Add a slash on the end of the URL (i.e. www.domain.com/subfolder/page.html to www.domain.com/subfolder/page/

It would be super if while writing www.domain.com/page.html the URL would automatically change to www.domain.com/page/

Thank you in advance!

My htaccess at the moment:

RewriteEngine on

RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]

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

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]

Solution

  • Replace all of your code block with this one:

    DirectoryIndex index.html
    RewriteEngine on
    
    # redirect file.html to /file/
    RewriteCond %{THE_REQUEST} \s/+(.+?)\.html\s [NC]
    RewriteRule ^ /%1/ [R=302,NE,L]
    
    # added .html extension to /file by checking presence of file.html
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{DOCUMENT_ROOT}/$1.html -f
    RewriteRule ^(.+?)/?$ $1.html [L]