++ed by:

4 PAUSE users

Αριστοτέλης Παγκαλτζής


Plack::Middleware::Rewrite - mod_rewrite for Plack


version 1.008


 # in app.psgi
 use Plack::Builder;
 builder {
     enable 'Rewrite', rules => sub {

         return 301
             if s{^/foo/?$}{/bar/}
             or s{^/baz/?$}{/quux/};

         return 201 if $_ eq '/favicon.ico';

         return 503 if -e '/path/to/app/maintenance.lock';

         return [200, [qw(Content-Type text/plain)], ['You found it!']]
            if $_ eq '/easter-egg';

         return sub { $_->set( 'Content-Type', 'application/xhtml+xml' ) }
             if $_[0]{'HTTP_ACCEPT'} =~ m{application/xhtml\+xml(?!\s*;\s*q=0)}


This middleware provides a convenient way to modify requests in flight in Plack apps. Rewrite rules are simply written in Perl, which means everything that can be done with mod_rewrite can be done with this middleware much more intuitively (if in syntactically wordier ways). Its primary purpose is rewriting paths, but almost anything is possible very easily.



rules takes a reference to a function that will be called on each request. When it is, the PATH_INFO is aliased to $_, so that you can easily use regexp matches and subtitutions to examine and modify it. The PSGI environment will be passed as its first and only argument. The function can return four (and a half) kinds of values:

Nothing or undef

In that case, any path and query string rewriting will be treated as an internal rewrite, invisible to the user. This is just like having RewriteRules that do not redirect.

A scalar value that looks like an HTTP status

This will stop the request from being processed further. An empty response with the returned status will be sent to the browser. If it is a redirect status, then the rewritten PATH_INFO will be used as the redirect destination.

An array reference

This is assumed to be a regular PSGI response, except that you may omit either or both the headers and body elements. Empty ones will be supplied for you, for convenience.

A code reference

The function you supply will be called after the request has been processed, with $_ aliased to a Plack::Util::headers object for the response, for convenient alteration of headers. The PSGI environment is, again, passed as its first and only argument.

Any other kind of value

Other values are currently treated the same as returning nothing. This may change in the future, depending on whether ambiguities crop up in practice. If you want to be absolutely certain to avoid ambiguities, return one-element arrays instead of plain values, and use an explicit return at the end of your rules:

 return [201] if $_ eq '/favicon.ico';


Aristotle Pagaltzis <pagaltzis@gmx.de>


This software is copyright (c) 2014 by Aristotle Pagaltzis.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.