Deploy Django on a subdirectory (or a subpath) with mod_python

It doesn’t matter for how long you’ve been using Django – as much as you think you know it, at some point Django will surprise you transforming simple tasks into issues taking hours to be solved. I’ve never had the need to deploy a Django instance anywhere but the root of the domain name (e.g. http://example.com/myapp). Till last weekend, when I spent almost two hours to figure out how to do it without making a mess of the urls.py module (configuring Apache and mod_wsgi to serve a subpath was straightforward and it’s not covered by this article).

Actually Django does a really good job handling URL prefixes and, to be honest, I wouldn’t write these lines if I didn’t make use of the bittersweet Django Admin. AFAIK, problems arise in the following:

  • Your webserver does not set SCRIPT_NAME environment variable
  • Using the django-admin
  • Using {% url %} template tag
  • Using @login_required decorator

For the latter there’s a quick solution: set LOGIN_URL and LOGOUT_URL variables in your settings.py with the desired url path. In all the other cases, you’ve to play with the SCRIPT_NAME environment variable,  defined in CGI standard, which holds the request URL’s path which points at the application target. Well hidden (IMHO) at the bottom of this page you can find a quick and clean solution to manually set the SCRIPT_NAME variable: just define FORCE_SCRIPT_NAME in your settings.py, e.g. FORCE_SCRIPT_NAME=’/myapp’ without the trailing slash. That’s all.

One thought on “Deploy Django on a subdirectory (or a subpath) with mod_python

  1. Hmm it appears like your site ate my first comment (it was super long) so I guess I’ll just sum
    it up what I submitted and say, I’m thoroughly
    enjoying your blog. I too am an aspiring blog blogger but I’m still new to everything.
    Do you have any suggestions for rookie blog writers? I’d genuinely appreciate it.

Comments are closed.