Notes to self

Changing URLs in Jekyll

How to change pages’ URLs in Jekyll using a custom generator plugin.

We had some content in current directory and some in /content folder which was essentially another git repository. The problem was that the /content folder stayed in the path which wasn’t what we wanted (and changing document root was not possible).

So we implemented a simple generator plugin changing all urls starting with /content/. To do so, we had to make an attribute writer for url param of Jekyll::Page class since this isn’t otherwise possible. That’s how our simple generator looks like:

$ cat _plugins/permalinks.rb
module Jekyll
  class Page
    def url=(name)
      @url = name
    end
  end
end

module Permalinks
  class Generator < Jekyll::Generator
    def generate(site)
      site.pages.each do |page|
        if page.url.start_with? '/content/'
          page.url = page.url[8..-1]
        end
      end
    end
  end
end

Another way is to just edit _config.yml file and change the permalink attribute, but than you need a special entry for every subdirectory.

Check out my book
Deployment from Scratch is unique Linux book about web application deployment. Learn how deployment works from the first principles rather than YAML files of a specific tool.
by Josef Strzibny
RSS