Apache mod_rewrite and proxypass

| No Comments

From the department of “this took me a while to figure out and googling didn’t help much, so here’s what I did”.

Problem

Combining mod_rewrite (rewriterule / rewritecond) with proxypass directives inside a single virtualhost block in your apache configuration.

Background

This isn’t unique to the problem/solution, but fyi, we have:

  • Front end apache, serving static files
  • Backend “application” apache, running our mod_perl application

We proxy requests for the application to the backend apache and deliver the rest of the files (css, js, ssi includes) from the frontend.

ProxyPass        /art         !
ProxyPass        /css         !
ProxyPass        /favicon.ico !
ProxyPass        /robots.txt  !
ProxyPass        /            http://localhost:8001/
ProxyPassReverse /            http://localhost:8001/

We were trying to set an environment variable (or setting a cookie would be another use-case) using RewriteRule.

We wanted to conditionally set the rule based on a querystring, so SetEnvIf wasn’t sufficient because it cannot see the query string component of the request.

In general, this can be achieved with:

RewriteEngine on
RewriteCond %{REQUEST_URI} ^/some/foo/
RewriteCond %{QUERY_STRING} .*qs_param=.*
RewriteRule (.*) $1 [E=my_env_var:1]
....
ProxyPass        /art         !

The RewriteRule line is basically saying: set this environment variable but otherwise do nothing.

The problem was that requests for /some/foo/ where 404’ing rather than being proxy passed.

Solution

Can be found in the apache docs for RewriteRule and specifically the section about PassThrough:

This flag is just a hack to enable post-processing of the output of RewriteRule directives, using Alias, ScriptAlias, Redirect, and other directives from various URI-to-filename translators.

… such as ProxyPass. So the fix for us was:

RewriteRule (.*) $1 [PT,E=my_env_var:1]

ps

When trying to figure out what is going on with Rewrite rules, the RewriteLog and RewriteLogLevel options are well worth taking advantage of.

Leave a comment

About this Entry

This page contains a single entry by mint published on August 18, 2009 3:40 PM.

How to create your own Moose sub types in Perl was the previous entry in this blog.

Paste & execute code with results as a short url is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.