.htaccess - Force Urls From 'dir/page.html' → 'dir/page'

- 1 answer

I would like to remove all trailing extension for a spefic file type (for instance remove all .html and let everything else as is)

So, for example, if an user goes on the page <my-site>/how-to/use-git.html, he would be redirected to <my-site>/how-to/use-git (with or without trailing /). Any other request (like <my-site>/how-to/img1.jpg) would be left as is (<my-site>/how-to/img1.jpg).

While browsing around, I couldn't find something satisfying the following conditions (both):

  • Remove the .html
  • Force to go to the url without extension

I tried things like this

# From
RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} \s/+pages/(.+?)\.html[\s?] [NC]
RewriteRule ^ /%1/ [R=302,L,NE]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/pages/$1\.html -f [NC]
RewriteRule ^(.+?)/?$ pages/$1.html [L]

But it doesn't force pages to go to the version without extension.


# From
RedirectMatch 301 (.*)\.html$ $1

creates 404 not found error.



You can use these rules in your DOCUMENT_ROOT/.htaccess file:

RewriteEngine On

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

## To internally redirect /path/file to /path/file.html
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+?)/?$ $1.html [L]