Skip to content
Snippets Groups Projects
README.markdown 12.91 KiB

rack-rewrite

A rack middleware for defining and applying rewrite rules. In many cases you can get away with rack-rewrite instead of writing Apache mod_rewrite rules.

Usage Examples

Usage Details

Sample rackup file

# config.ru
gem 'rack-rewrite', '~> 1.5.0'
require 'rack/rewrite'
use Rack::Rewrite do
  rewrite   '/wiki/John_Trupiano',  '/john'
  r301      '/wiki/Yair_Flicker',   '/yair'
  r302      '/wiki/Greg_Jastrab',   '/greg'
  r301      %r{/wiki/(\w+)_\w+},    '/$1'
end

Sample usage in a rails app

# config/application.rb
config.middleware.insert_before(Rack::Lock, Rack::Rewrite) do
  rewrite   '/wiki/John_Trupiano',  '/john'
  r301      '/wiki/Yair_Flicker',   '/yair'
  r302      '/wiki/Greg_Jastrab',   '/greg'
  r301      %r{/wiki/(\w+)_\w+},    '/$1'
end

If you use config.threadsafe, you'll need to insert_before(Rack::Runtime, Rack::Rewrite) as Rack::Lock does not exist when config.allow_concurrency == true:

config.middleware.insert_before(Rack::Runtime, Rack::Rewrite) do
  rewrite   '/wiki/John_Trupiano',  '/john'
  r301      '/wiki/Yair_Flicker',   '/yair'
  r302      '/wiki/Greg_Jastrab',   '/greg'
  r301      %r{/wiki/(\w+)_\w+},    '/$1'
end

Or insert Rack::Rewrite to the top of the stack:

config.middleware.insert 0, 'Rack::Rewrite' {}

Redirection codes

All redirect status codes from the HTTP spec are supported:

  • 301 moved permanently
  • 302 found
  • 303 see other
  • 307 temporary redirect

These translate to the following methods inside the Rack::Rewrite block:

r301                '/wiki/John_Trupiano', '/john'
moved_permanently   '/wiki/John_Trupiano', '/john'
p                   '/wiki/John_Trupiano', '/john'    # shortcut alias

r302                '/wiki/John_Trupiano', '/john'
found               '/wiki/John_Trupiano', '/john'

r303                '/wiki/John_Trupiano', '/john'
see_other           '/wiki/John_Trupiano', '/john'

r307                '/wiki/John_Trupiano', '/john'
temporary_redirect  '/wiki/John_Trupiano', '/john'
t                   '/wiki/John_Trupiano', '/john'    # shortcut alias

The 303 and 307 codes were added to the HTTP spec to make unambiguously clear what clients should do with the request method. 303 means that the new request should always be made via GET. 307 means that the new request should use the same method as the original request. Status code 302 was left as it is, since it was already in use by the time these issues came to light. In practice it behaves the same as 303.

Use Cases