cmc/cleberg.net

My personal web garden & blog.

clone: git clone https://gitbay.org/cmc/cleberg.net.git

main: content/blog/2021-10-09-apache-redirect.org · raw

 1#+date:        [2021-10-09 Sat 00:00:00]
 2#+title:       Apache Rewrite Rules for Extensionless URLs
 3#+description: Using mod_rewrite to serve clean, extensionless URLs in Apache.
 4#+slug:        apache-redirect
 5#+filetags:    :web:
 6
 7* The Problem
 8
 9After recently switching static site generators (SSG), my blog URLs (uniform
10resource locators) changed with no option to preserve the classic =.html=
11extension at the end of my blog post URLs.
12
13I really disliked using my old SSG ([[https://jekyllrb.com][Jekyll]]) and prefer my new tool ([[https://www.getzola.org][Zola]]) much
14more, so I was determined to figure out a way to get the proper redirect set up
15so that people who find my posts online aren't constantly met by 404 errors.
16
17* The Solution
18
19To solve this problem, I really needed to solve two pieces:
20
211. Redirect all blog post URL requests from =/blog/some-post.html= to
22   =/blog/some-post/=.
232. Ensure that no other =.html= files are redirected, such as =index.html=.
24
25After /a lot/ of tweaking and testing, I believe I have finally found the
26solution. The solution is shown below.
27
28#+begin_src conf
29RewriteEngine On
30RewriteCond %{REQUEST_URI} !\index.html$ [NC]
31RewriteRule ^(.*).html$ https://example.com/$1 [R=301,L]
32#+end_src
33
34This piece of code in the Apache =.conf= or =.htaccess= file will do the
35following:
36
371. Turn on the RewriteEngine so that we can modify URLs.
382. Ignore any =index.html= files from the rule we are about to specify.
393. Find any =.html= files within the website directory and redirect it to
40   exclude the file extension.
414. The final piece is adding the trailing slash (=/=) at the end of the URL -
42   you'll notice that I don't have an Apache rule for that since Apache handles
43   that automatically.