Hide .html and manage 404

Viewed 58

i would like to do this mapping on my website

xyz.html -> on /xyz
abc.html -> on /abc
index.html -> on /

i wrote these rules on my .htaccess file

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule !^$ !.*\.html$ %{REQUEST_FILENAME}.html [L]

but i have some issues.

  • 404 error doesn't work anymore. if i browse /hello it gave me Internal Server Error
  • I would like a redirect if i browse to /xyz.html -> /xyz (SEO friendly)

wanted actions:

/ -> serve index.html        
/abc -> serve abc.html       
/abc.html -> redirect to /abc      
/123.html -> throws 404      
/123/ -> throws 404 (now throws 500)

How can i do this? Thank you in advance

1 Answers

You can use the following :

RewriteEngine on

#Remove .html extension
#1)redirect "/file.html" to "/file"
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^([^.]+)\.html$ /$1 [L,R=301]
#2) internally map /file to /file.html
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^/]+)/?$ /$1.html [L]
#3) Redirect "index.html to "/"
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^index\.html$ / [L,R=301]
#Internally map homepage "/" to "index.html"
RewriteRule ^$ /index.html [L]
Related