Read more

Middleman: Use pretty URLs without doubling requests

Henning Koch
May 30, 2017Software engineer at makandra GmbH

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.

Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

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.

Posted by Henning Koch to makandra dev (2017-05-30 10:04)