Skip to content
Nginx

Server Block

Configure a virtual host with root, index, and try_files.

By EZ4Code Team
serverstatichosting

Code

# /etc/nginx/conf.d/example.conf
server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/example;
    index index.html index.htm;

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

    # Static assets caching
    location ~* \.(css|js|png|jpg|svg|woff2)$ {
        expires 7d;
        add_header Cache-Control "public, no-transform";
    }

    # Custom error page
    error_page 404 /404.html;
    location = /404.html {
        internal;
    }
}

Explanation

A server block defines a virtual host listening on a port for specific server_name values. root sets the base directory and index lists files tried for directory requests. try_files attempts each path in order, falling back to a SPA-friendly index.html for client-side routing.

More Nginx Snippets