Nginx Static File Serving Configuration

Optimize Nginx for high-performance static file serving with proper MIME types, try_files fallback, sendfile kernel optimization, and SPA routing tips.

Performance

Detailed Explanation

Nginx is exceptionally fast at serving static files due to its asynchronous, event-driven architecture that handles thousands of concurrent file transfers with minimal memory overhead.

Basic Static File Configuration

Use the root or alias directive to define where your static files are located on disk:

server {
    listen 80;
    server_name static.example.com;
    root /var/www/html;

    location / {
        try_files $uri $uri/ =404;
    }
}

root vs alias

The root directive appends the full location path to the specified directory. The alias directive replaces the matched location path entirely. This distinction is critical and a common source of configuration bugs:

# With root, /images/logo.png serves /var/www/html/images/logo.png
location /images/ {
    root /var/www/html;
}

# With alias, /images/logo.png serves /var/www/assets/logo.png
location /images/ {
    alias /var/www/assets/;
}

Performance Optimizations

Enable sendfile to let the kernel transfer files directly from disk to the network socket, bypassing user-space memory buffers entirely. Combined with tcp_nopush, this minimizes the total number of network packets transmitted.

sendfile on;
tcp_nopush on;
tcp_nodelay on;

MIME Types

Nginx relies on the mime.types file to set the correct Content-Type header for each file extension. Ensure this file is included in your configuration to prevent browsers from misinterpreting file types:

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
}

Directory Listing

Enable directory browsing for file download servers or internal asset repositories with the autoindex directive:

location /downloads/ {
    autoindex on;
    autoindex_exact_size off;
    autoindex_localtime on;
}

try_files for Single-Page Applications

For SPAs built with React, Vue, or Angular, use try_files to fall back to index.html for all routes so the JavaScript router can handle client-side routing:

location / {
    try_files $uri $uri/ /index.html;
}

This serves the requested file if it exists on disk, otherwise returns index.html so the frontend framework can render the appropriate view based on the URL.

Use Case

You are hosting a single-page application or a file download server and need Nginx to efficiently serve HTML, CSS, JavaScript, images, and other static assets.

Try It — Nginx Config Generator

Open full tool