Nginx · The edge of your stack

How do you serve static files efficiently and safely?

Easystatic filesrootaliasUpdated Oct 2026
Quiz this track

Short answer

Set root or alias correctly, enable sendfile, use try_files for missing paths, add long-lived cache headers for hashed assets and deny directory listing or hidden files.

Static serving is one of Nginx's strongest use cases. The main correctness issue is the difference between root and alias: root appends the full URI to the path, while alias replaces the matched location prefix.

nginx
server {
    root /var/www/site;

    location /assets/ {
        alias /var/www/static/assets/;
        add_header Cache-Control "public, max-age=31536000, immutable";
    }

    location / {
        try_files $uri $uri/ =404;
    }
}
A request for /assets/app.css maps to /var/www/static/assets/app.css with alias.

Performance and safety

  • sendfile on avoids copying file data through user space
  • tcp_nopush and tcp_nodelay improve packet behavior for different workloads
  • open_file_cache reduces repeated stat calls for hot files
  • autoindex off prevents directory listings unless explicitly needed
  • Deny access to dotfiles and backup files, and keep permissions minimal
With alias, the trailing slashes on the location and alias paths usually need to match. A mismatch can expose the wrong directory or produce 404s.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What is the difference between root and alias?
  2. 2Why is sendfile useful?
  3. 3How would you prevent directory listing?
  4. 4When should static assets be served by a CDN instead of Nginx?

Say it in the interview

I use root when the URI should be appended to a directory and alias when the location prefix should be replaced. I enable sendfile and open_file_cache for hot files, use try_files to avoid accidental directory handling, and add immutable caching for hashed assets. I also disable autoindex and deny hidden or backup files.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Nginx mock interview and get scored feedback on depth, clarity and confidence.