TIP : How to get Apache Location directive to match trailing slashes

mikechambers May 1st, 2008

I am working on deploying a django app online, and thus need to use the Apache Location directive to point to my django app.

This is pretty straight forward:

<Location "/foo/">
        SetHandler python-program
        PythonPath "['/path/to/djangositedir/'] + sys.path"
        PythonHandler django.core.handlers.modpython
        SetEnv DJANGO_SETTINGS_MODULE settings
        PythonDebug On
</Location>

Note: You will normally add / edit this in the httpd.conf file for your apache installation.

Basically, you just map “/foo/” to the python handler. Anytime someone goes to a URL that begins with “”/foo/”" on your site, it will be handled by Python and your django app.

However, if someone leaves of the trailing slash like so “/foo” then the location doesnt match and the server will return a 404.

Luckily, this is fairly easy to fix, and I wanted to post it here for future reference. Just use a regular expression to match either “/foo” or “/foo/”. Here is the updated directive:

<Location ~ "/foo(/|$)">
        ...
</Location>

Note that the “~” is important as it enabled regular expression support. Basically, this says match anything that begins with “/foo” and either has a trailing “/” or ends “$”.

3 Responses to “TIP : How to get Apache Location directive to match trailing slashes”

  1. edbondon 02 May 2008 at 6:00 am

    Try “/foo/?”

    ? means 0 or 1 appearance of previous token.

    Eduard

  2. mikechamberson 02 May 2008 at 7:03 am

    It means end of string.

    That way it matches:

    /foo
    /foo/

    but not

    /foofer

    mike chambers

    mesh@adobe.com

  3. Thomas Broyeron 02 Jun 2008 at 2:01 am

    How about leaving your /foo/ mapping as is and just adding a permanent redirect from /foo to /foo/ ?

Trackback URI | Comments RSS

Leave a Reply