When developing a Django application in debug mode, I serve static files using the following code:
if settings.DEBUG:
urlpatterns += patterns('',
(r'^m/(?P<path>.*)$', serve, {
'document_root' : os.path.join(os.path.dirname(__file__), "media")
})
)
I am using nginx as a front end to server my static files in production mode using the following nginx config:
location m/
{
root /path/to/folder/media/;
}
Which seems sub-optimal because I have to create a “m” folder in the media directory. I am wondering what everyone else’s Django/nginx config files look like. Specifically, can you please cut-and-paste sections of nginx.confg and urls.py (settings.DEBUG == True)
Thanks.
Using Django 1.3
django.contrib.staticfileswill take care of serving everything for you during development. You don’t need to do anything particular in the urls.py. I wrote a little guide for myself after the Django 1.3 update that covers the settings to use:Refer to the docs for details: http://docs.djangoproject.com/en/1.3/howto/static-files/.
I use nginx and uwsgi for serving django apps in production (I use runserver for development). I symlink my
/staticand/mediafolders (from my django project) into/var/www/vhosts/domain.com/htmlfor nginx to find. You could also use thecollectstaticcommand instead of symlinking. If it can’t find a static file it falls back to uwsgi (which is running the django app).Instead of uwsgi you could use fast-cgi, or proxy_pass or whatever you want. I prefer uwsgi because it has an incredible number of features and great performance. I run uwsgi as a daemon with:
uwsgi --emperor '/srv/*/*.ini'. This is a fairly new option, it tells uwsgi to scan a given path for configuration files. When the emperor uwsgi daemon finds a configuration file it launches a new instance of uwsgi using the configuration found. If you change your configuration the emperor uwsgi daemon will notice and restart your app for you. You can also touch the config file to reload like with mod_wsgi, and it’s really easy to setup new apps once you have everything configured initially.The path conventions I follow are:
This is my nginx.conf:
My uwsgi ini file (you can also use xml/yaml/etc):
You should also check out gunicorn, it has really nice django integration and good performance.