Posted about 3 years 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.

Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Henning Koch
Last edit:
about 3 years 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 makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more