Middleman: Use pretty URLs without doubling requests

Updated . Posted . Visible to the public.

By default Middleman Show archive.org snapshot generates files with a .html extension. Because of this all your URLs end in /foo.html instead of /foo, which looks a bit old school.

To get prettier URLs, Middleman lets you activate :directory_indexes in config.rb. This makes a directory for each of your pages and puts a single file index.html into it, e.g. /foo/index.html. This lets you access pages with http://domain/foo.

Don't double your requests!

Unfortunately you are now forcing every browser to make two requests for every page. The browser will first request /foo, then the server will return a redirect to /foo/ (mind the trailing slash), then the browser makes a second request to /foo/ to retrieve the actual HTML.

You can probably fix this by configuring your static web server. What we want is:

  1. Accessing /foo should directly return the content of /foo/index.html without a redirect
  2. Accessing /foo/ should redirect to the canonical /foo.

If you are using Apache, ask your admin to allow the use of .htaccess files. Also ask to get the modules mod_dir and mod_rewrite installed (they probably are already).

Now add a file build/.htaccess with the following content:

DirectorySlash Off
Options -Indexes

RewriteEngine On

RewriteCond %{DOCUMENT_ROOT}/$1/index.html -f
RewriteRule ^(.+?)/$ /$1 [R=301,L]

RewriteCond %{DOCUMENT_ROOT}/$1/index.html -f
RewriteRule ^(.+?)$  /$1/index.html [L]

Now deploy.

Henning Koch
Last edit
Henning Koch
Keywords
duplicate, send, requests, twice
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2017-05-30 08:04)