-1

When a page is visited using a URL that ends with .html, I'd like the URL to change to having no extension and report 301 permanently redirected. I'm having serious difficulty. After reading a lot of documentation and tutorials, and searching Stack Overflow for hours, the closest I've achieved is the opposite (URLs with no extension having one added) with this code:

<Location />
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME}\.html -f
    RewriteCond %{REQUEST_URI} !/$
    RewriteCond %{REQUEST_URI} !\.html$
    RewriteRule ^(.*)$ https://%{HTTP:Host}%{REQUEST_URI}.html [L,R=permanent]
</Location>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
timeSmith
  • 553
  • 1
  • 8
  • 16
  • 1
    https://webmasters.stackexchange.com/questions/68577/remove-extension-from-url-using-a-rewrite-without-resulting-in-a-redirect-loop – Nic3500 Aug 05 '18 at 02:42

1 Answers1

0

This can be done in two steps, with a REDIRECT_LOOP environment variable to prevent looping, with the directives in a Directory section for the web root (or .htaccess in the web root) so the matched string in the RewriteRule can be used for the permanent Redirect.

<Directory "/var/www/html">

 RewriteEngine On

 RewriteCond %{REQUEST_FILENAME} !-d # if the request is not a directory
 RewriteCond %{REQUEST_FILENAME} !-f # if the request is not a file
 RewriteCond %{REQUEST_FILENAME}\.html -f # if adding .html it is a file
 RewriteCond %{REQUEST_URI} !\.html$ # if the request doesn't end in .html
 RewriteCond %{REQUEST_URI} !/$ # if the request doesn't end in /
 RewriteRule ^(.*)$ $1.html [L,E=LOOP:1] # then return the request as if it ended with .html and set the loop variable

 RewriteCond %{ENV:REDIRECT_LOOP} !1 # if we didn't just added .html
 RewriteRule ^(.*)\.html$ https://%{HTTP:Host}/$1 [L,R=permanent] # then 301 redirect the request to the request without the .html

</Directory>

This will make it so that if you have example.html and example/index.html then example.html will never be loaded.

timeSmith
  • 553
  • 1
  • 8
  • 16