Why do the Django docs suggest a separate server for static files?
It's also good for security. A pretty cut-and-dry approach is to keep user uploaded files away from your core server files. Separate folder permissions etc. But yea, big speed advantages.
In general, it's a good idea to put static content - e.g. images, CSS and JS files - on a different server and, furthermore, on a different domain/subdomain. This allows the software that serves the static files to be highly optimized and blazingly fast (for example, nginx).
The other main benefit comes from decreases in network traffic. If you serve static content from the same domain as your dynamic Django app, then client browsers send your domain's cookies as part of their HTTP request, even for static files. This is unnecessary overhead - static files will always be static - but is required because the client can't tell the difference between static and dynamic content. If, on the other hand, the static content was being served from a different domain, then it could be configured as a "cookieless domain", thus minimizing request overhead.
Modern web browsers will often open two (several?) sockets when downloading assets from a single host. So you get index.html
which references a bunch of images, js files, css etc. Each additional file is downloaded by a single blocking socket.
If you pull static files from a separate host, you get an extra two sockets to download the files - and so in production this works much faster.
This parallelisation also allows you to run different server engines (ok, they could be on the same box - but then you still only get two sockets) that specialise in what they're serving - for instance nginx
for raw content and fastcgi
for the django
dynamic content.
This is a common strategy among web frameworks. The idea here is to simply use the best tool for the job of serving static content. Apache, Nginx, lighttpd, and other modern webservers are all extremely good at serving static content, so if you can easily configure these servers to do that job you have several benefits:
- Those requests are blazing fast.
- You're not occupying your heavyweight python processes doing mundane tasks, so they are free to process application requests.
- Down the road, by having this separate process for handling static content, you have more flexibility in terms of using CDNs or spreading assets to other servers.
By moving your media to a particular directory you have a simpler time configuring the webserver for this task.