Home > Back-end >  .htaccess - remove .html and allow at the end of the url with and without trailing slash
.htaccess - remove .html and allow at the end of the url with and without trailing slash

Time:09-04

I would like to use .htaccess to remove the .html extension in the URL and be able to access the URL with or without a trailing slash at the end

Now when I call the page with a slash at the end I get a 500 Internal Server Error

My .htaccess Code:

DirectorySlash Off
Options  FollowSymLinks -MultiViews -Indexes
RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.] )\.html [NC]
RewriteRule ^ %1 [R,L,NC]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [L]

CodePudding user response:

Have it like this:

DirectorySlash Off
Options  FollowSymLinks -MultiViews -Indexes
RewriteEngine On

# To externally redirect /dir/file.html to /dir/file
RewriteCond %{THE_REQUEST} \s/ (. ?)\.html[\s?] [NC]
RewriteRule ^ /%1 [R=302,NE,L]

# To internally forward /dir/file to /dir/file.html
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.html -f
RewriteRule ^(. ?)/?$ $1.php [L]

Some Apache implementations can be buggy resolving %{REQUEST_FILENAME} hence it is better to construct full file path using %{DOCUMENT_ROOT}.

  • Related