Serving Static Files Directly With Nginx
00:00 Serving Static Files Directly With Nginx. You now have Nginx proxying requests to your Django app. Importantly, you can also use Nginx to serve static files directly.
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.
03:14 You’d want to take advantage of that feature in a larger project. The next step is to create a directory path that will house your project’s static content for Nginx to serve.
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.
Now, you should turn off
Gunicorn will pick up this change, as earlier on, you set
reload to be
True. Next, restart Nginx. Refresh the site again and see what happens when you hover over the page text.
enlarge() function has kicked in. To get this result, the browser had to request the
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.