Things I've Learned About nginx

Mar 29, 2024

Now that I am fully managing this website's back-end, I've had to educate myself on configuring nginx. Here are a few of the things I've learned since starting down this path:

Using try_files

At first, I couldn't figure out the magic for having nginx serve a static file if it was actually present on the server, but fall back to my Django application if it wasn't. The answer is to use try_files, a handy built-in resource for this exact use case. I found this via this helpful entry in the Pitfalls and Common Mistakes article (which itself is a treasure trove of information). The specific entry ended up looking like this:

server {
    location / {
        try_files $uri @proxy_to_app;

    location @proxy_to_app {
        # Typical proxy-pass stuff here

Shortcutting Known Bad Paths

Don't let your Django app handle paths you know are bad; let nginx offload that processing work for you! I was seeing plenty of accesses against .php files in my server access logs, so I wrote a quick block to reject them:

server {
    location ~* \.php$ {
        return 404;

Enabling Strict-Transport Security

Until recently, I didn't even know that HTTP Strict Transport Security was a thing, but it turns out to be pretty easy to implement. Once you have your SSL stuff ironed out and working, you simply need to enable the appropriate header:

add_header Strict-Transport-Security "max-age=5184000; includeSubDomains";

No comments (yet!)

Leave a Comment

Ignore this field:
Never displayed
Leave this blank:
Optional; will not be indexed
Ignore this field:
Both Markdown and a limited set of HTML tags are supported
Leave this empty: