Serving Static Files Directly With Nginx
If you have
DEBUG set to
True in your
settings.py file, then Django will render the files, but this is inefficient and probably insecure. Instead, you can have the web server render them directly.
Next, add the following configuration to
STATIC_ROOT with your domain name. You’re telling Django’s
collectstatic command where to search for and place the resulting static files that are aggregated from multiple Django apps, including Django’s own built-in apps, such as
Now the span with the ID of
"changeme" will have an event listener added to it. Note that to keep this example straightforward, you are hard-coding the URL path to
greenlight.js file instead of using Django’s
static template tag.
collectstatic as your non-root user from within your project’s directory. Finally, add a
location variable for
/static in the Nginx configuration file for your site. Once again, remember that your domain won’t be
deploydjango.site, so you’ll need to customize these steps for them to work in your own project.
collectstatic, Django is no longer responsible for determining how to map the URL to a complex view and render that view.
Nginx can just hand the file off directly to the browser. In fact, if you navigate to your domain’s equivalent of the one seen on-screen, you’ll see a traditional file system view of
/static created by Nginx.
05:58 This means faster and more efficient delivery of static files. At this point, you’ve got a great foundation for a scalable site using Django, Gunicorn, and Nginx. In the next section of the course, you’ll take a look back at what you’ve learned.
Become a Member to join the conversation.