Index Files and Try Files

1 min read

Authors
banner

Index Files and Try Files

Index Directive

Serve a default file when accessing a directory:

server {
    index index.html index.htm;
}

When visiting / the server will try index.html then index.htm.

Try Files Directive

Try multiple file locations in order:

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

This tries in order:

  1. Exact file ($uri)
  2. Directory ($uri/)
  3. Fall back to /index.html
  4. Return 404 if nothing found

Single Page Application Setup

Perfect for React, Vue, Angular SPAs:

server {
    root /var/www/app;

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

    # Cache static files
    location ~* \.(js|css|png|jpg)$ {
        expires 1y;
    }
}

Perfect for modern apps!

© 2025 Vijay Rajendran