Posted 8 months ago. Visible to the public.

Middleman: Use pretty URLs without doubling requests

By default Middleman 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.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Author of this card:

Henning Koch
Last edit:
8 months ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandropedia