Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

.htaccess - ReWrite rule to add .html extension

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)

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)$

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...