nginx — How to Serve a Static HTML Page

Nginx is a powerful reverse proxy routing your domains from the Internet to your applications. This tutorial shows you how to serve a static HTML page with nginx. It walks you through the required paths, files, and configurations.

nginx Series Overview

Serve Static HTML Pages with nginx

We created a snake browser game and wanted to make it available for everyone to play. The game is a single HTML file referencing a handful of JavaScript files.

To serve static files with nginx, you should configure the path of your application’s root directory and reference the HTML entry point as the index file.

In this example, the root directory for the snake deployment is /home/futurestudio/apps/snake which contains all the files. The root directory also contains the index file, called game.html.

Nginx serves the index file when visiting the configured domain. In this case, nginx serves the game.html when visiting snake.futurestud.io:

server {  
    listen 80;
    server_name snake.futurestud.io;

    access_log /var/log/nginx/snake_futurestud_io_access.log;
    error_log  /var/log/nginx/snake_futurestud_io_error.log;

    root /home/futurestudio/apps/snake;
    index game.html;

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

The location property ensures to serve requested files if available. For unavailable files, nginx responds with the 404 HTTP status code.

Let’s shine some more light on this configuration: the game.html has references to individual JavaScript files implementing the actual game logic. When serving the game.html, the browser sends the requests to fetch these JavaScript files. Nginx will then serve the requested files from the same root directory.

That’s it! Ensure the root and index properties and nginx serves static HTML and JavaScript files.


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.