content/blog/2021-10-09-apache-redirect.org
46 lines · 1896 bytes
Configuration of Apache Rewrite Rules for Redirecting HTML URLs to Directory URLs
The Problem
After recently switching static site generators (SSG), my blog URLs
changed with no option to preserve the classic .html extension at the
end of my blog post URLs.
I really disliked using my old SSG (Jekyll) and prefer my new tool (Zola) much more, so I was determined to figure out a way to get the proper redirect set up so that people who find my posts online aren't constantly met by 404 errors.
The Solution
To solve this problem, I really needed to solve two pieces:
- Redirect all blog post URL requests from
/blog/some-post.htmlto/blog/some-post/. - Ensure that no other
.htmlfiles are redirected, such asindex.html.
After a lot of tweaking and testing, I believe I have finally found the solution. The solution is shown below.
RewriteEngine On
RewriteCond %{REQUEST_URI} !\index.html$ [NC]
RewriteRule ^(.*).html$ https://example.com/$1 [R=301,L]
This piece of code in the Apache .conf or .htaccess file will do the
following:
- Turn on the RewriteEngine so that we can modify URLs.
- Ignore any
index.htmlfiles from the rule we are about to specify. - Find any
.htmlfiles within the website directory and redirect it to exclude the file extension. - The final piece is adding the trailing slash (
/) at the end of the URL - you'll notice that I don't have an Apache rule for that since Apache handles that automatically.