I need a rule that will add an .html extension whenever there is 'not' a trailing slash.
A new client recently changed ecommerce scripts and the new version handles SEO differently and changed all of their 16,000+ product links. This was not caught prior to the site being re-indexed so we need to redirect the old to the new..
All products used to have links like this domain.com/category/productname but are now domain.com/category/productname.html
Category links did not change and all are like this domain.com/category/ (with trailing slash)
htaccess rewrite rules can be used to direct requests for one subdirectory to a different location, such as an alternative subdirectory or even the domain root. In this example, requests to http://mydomain.com/folder1/ will be automatically redirected to http://mydomain.com/folder2/.
A rewrite rule can be invoked in httpd. conf or in . htaccess . The path generated by a rewrite rule can include a query string, or can lead to internal sub-processing, external request redirection, or internal proxy throughput.
$1 represents the match from the first set of parentheses in the RewriteRule regex, not in the RewriteCond regex.
html extension can be easily removed by editing the . htaccess file.
There's a lot of answers here that sort of work, but by far the easiest way since apache 2.4 is to just enable MultiViews, see official docs https://httpd.apache.org/docs/2.4/content-negotiation.html
All I had to do was:
<Directory /var/www/html>
Options +MultiViews
</Directory>
This means that if I go to my site e.g. example.com/dashboard it just serves dashboard.html without needing any redirects, and it keeps the original URL as it was (so it doesn't append the extension).
I couldn't really find specifics in the docs about which file extensions get priority, so not sure what happens if you have both dashboard.html and dashboard.php living in the directory, or whether it's easy to change the priority order.
The answer from @david-wolever redirects everything that does not end in .html (or the root) to the same URL with an added .html extension, meaning it appends a .html extension to things like CSS and JavaScripts files, e.g. it will redirect /style.css to /style.css.html which is not likely what you want. It also has the spaces after ! character which will likely caused @greggles 500s
This redirects URLs which do not end in a dot followed by 3 or 4 alphanumeric characters:
RewriteEngine On
RewriteCond %{REQUEST_URI} !\.[a-zA-Z0-9]{3,4}
RewriteCond %{REQUEST_URI} !/$
RewriteRule ^(.*)$ $1.html
Or for finer grain control, whitelist the extensions you do not want .html appended to e.g.
RewriteCond %{REQUEST_URI} !\.(html|css|js|less|jpg|png|gif)$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With