Skip to content


Subversion checkout URL

You can clone with
Download ZIP
Shortener makes it easy to create shortened URLs for your rails application.


Build Status


Shortener is a Rails Engine Gem that makes it easy to create and interpret shortened URLs on your own domain from within your Rails application. Once installed Shortener will generate, store URLS and “unshorten” shortened URLs for your applications visitors, all whilst collecting basic usage metrics.


The majority of the Shortener consists of three parts:

  • a model for storing the details of the shortened link;

  • a controller to accept incoming requests and redirecting them to the target URL;

  • a helper for generating shortened URLs from controllers and views.


Shortener is designed to work from within a Rails 3 and Rails 4 applications. It has dependancies Rails core components like ActiveRecord, ActionController, the rails routing engine and more.

Ruby Version Support

As Ruby 1.9.3 entered end of maintainance in early 2015, the last version of the Shortener gem to support Ruby 1.9.3 is 0.4.x. Shortener v0.5 onwards will require Ruby 2+.


v0.4.0 to v0.5.0

There have been some breaking changes:

  1. The owner argument is passed into the generator and helper methods as a named parameter.

  2. Original URLs arguments without a hypertext protocol (http|https) will be assumed to be relative paths.

v0.5.1 to v0.5.2

v0.5.2 introduced the ability to set an expiration date for a shortened URL. The expiration dates are stored in a expires_at column in the database, which can be added to your schema with the following migration:

class AddExpiresAtToShortenedUrl < ActiveRecord::Migration
  def change
    add_column :shortened_urls, :expires_at, :datetime

Some niceities of Shortener:

  • The controller does a 301 redirect, which is the recommended type of redirect for maintaining maximum google juice to the original URL;

  • A unique alphanumeric code of generated for each shortened link, this means that we can get more unique combinations than if we just used numbers;

  • The link records a count of how many times it has been “un-shortened”;

  • The link can be associated with a user, this allows for stats of the link usage for a particular user and other interesting things;

  • The controller spawns a new thread to record information to the database, allowing the redirect to happen as quickly as possible;

Future improvements:

  • There has not been an attempt to remove ambiguous characters (i.e. 1 l and capital i, or 0 and O etc.) from the unique key generated for the link. This means people might copy the link incorrectly if copying the link by hand;

  • The system could pre-generate unique keys in advance, avoiding the database penalty when checking that a newly generated key is unique;

  • The system could store the shortened URL if the url is to be continually rendered;

  • Some implementations might want duplicate links to be generated each time a user request a shortened link.


Shortener is compatible with Rails v3 and v4. To install, add to your Gemfile:

gem 'shortener'

After you install Shortener run the generator:

rails generate shortener

This generator will create a migration to create the shortened_urls table where your shortened URLs will be stored.

Then add to your routes:

get '/:id' => "shortener/shortened_urls#show"


The gem can be configured in a config/initializers/shortener.rb file.

By default, the shortener will generate keys that are 5 characters long. You can change that by specifying the length of the key like so;

Shortener.unique_key_length = 6

By default, when a unique key isn't matched the site is redirected to “/”. You can change that by specifying a different url like so;

Shortener.default_redirect = ""

By default, Shortener will generate unique keys using numbers and lowercase a-z. If you desire more combinations, you can enable the upper and lower case charset, by including the following:

Shortener.charset = :alphanumcase


To generate a Shortened URL object for the URL “” within your controller / models do the following:


Alternatively, you can create a shortened url to a relative path within your application:


To generate and display a shortened URL in your application use the helper method:


Pass in subdomain, protocol and other options that the UrlHelper url_for accepts:

short_url("", url_options: { subdomain: 'foo', host: 'bar, protocol: 'https' } )

This will generate a shortened URL. store it to the db and return a string representing the shortened URL.

Shortened URLs with owner

You can link shortened URLs to an owner, to scope them. To do so, add the following line to the models which will act as owners:

class User < ActiveRecord::Base

This will allow you to pass the owner when generating URLs:

Shortener::ShortenedUrl.generate("", owner: user)

short_url("", owner: user)

And to access those URLs:


Shortened URLs with custom unqiue key

You can pass in your own key when generating a shortened URL. This should be unique.

Shortener::ShortenedUrl.generate("", owner: user, custom_key: "my-key")

short_url("", custom_key: 'yourkey')

Expirable Shortened URLs

You can create expirable URLs. Probably, most of the time it would be used with owner:

Shortener::ShortenedUrl.generate("", user, expires_at: 24.hours.since)

You can omit owner passing nil instead:

Shortener::ShortenedUrl.generate("", nil, expires_at: 24.hours.since)

Fresh Links

Sometimes you just need that feeling of a fresh, untouched Shortened URL. By default, Shortener will find an existing ShortenedUrl record for a supplied URL. If you want to create a fresh record, you can pass the following argument:

Shortener::ShortenedUrl.generate("", fresh: true)
short_url("", fresh: true)

Forbidden keys

You can ensure that records with forbidden keys will not be generated. In rails you can put next line into config/initializers/shortener.rb

Shortener.forbidden_keys.concat %w(terms promo)

Helper Parameters

Parameters are passed though from the shortened url, to the destination URL. If the destination URL has the same parameters as the destination URL, the parameters on the shortened url take precedence over those on the destination URL.

Shorten URLs in generated emails

You can register the included mail interceptor to shorten all links in the emails generated by your Rails app. For example, add to your mailer:

class MyMailer < ActionMailer::Base

This will replace all long URLs in the emails generated by MyMailer with shortened versions. The base URL for the shortener will be infered from the mailer's default_url_options. If you use a different hostname for your shortener, you can use:

class MyMailer < ActionMailer::Base
  register_interceptor :base_url => ""

The interceptor supports a few more arguments, see the implementation for details.


For a bit of backstory to Shortener see this blog post.

In The Wild

Shortener is used in a number of production systems, including, but not limited to:

Doorkeeper - An Event Management Tool

If you are using Shortener in your project and would like to be added to this list, please get in touch!



New feature requests are welcome, code is more welcome still. Code with Specs is the most welcomiest there is!

To contribute:

  1. Fork it

  2. Create your feature branch (git checkout -b my-new-feature)

  3. Commit your changes (git commit -am 'Add some feature')

  4. Push to the branch (git push origin my-new-feature)

  5. Create a new Pull Request

Something went wrong with that request. Please try again.