mike chambers | about

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

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 "[&#x27;/path/to/djangositedir/&#x27;] + sys.path"
        PythonHandler django.core.handlers.modpython
        SetEnv DJANGO_SETTINGS_MODULE settings
        PythonDebug On

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 doesn’t 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(/|$)">

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 “$”.

twitter github flickr behance