Configuring Nginx to serve files for a static website

In the world of HTTP, static files are content hosted on a web server that does not change. Some examples of static files include images, CSS files, JavaScript files and HTML files.

Although it is not too hard to implement a dynamic website through a content management framework like WordPress on your own server, there are cases where it makes more sense to just host a couple of static files to realise your website.

Nginx is an excellent web server for serving static websites. If you already have Nginx running on a Raspberry Pi 3 or any other kinds of server, you may want to configure it to serve files for your static website.

Nginx configuration to serve files for a static website

Suppose you have:

  • the domain names example.com and www.example.com that are mapped to the IP address of the server where your Nginx installation is running from, and
  • the directory /var/www/example.com on your server that contains the static files for your static website.

You can make your Nginx web server serve static files for your static website with the following configurations:

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

What does the server_name and listen directives tell Nginx?

The server_name directive along with the listen directive instructs Nginx to handle HTTP GET requests directed at either http://example.com or http://www.example.com to take the instructions specified by this server block.

What does the root directive tells Nginx?

The root directive tells Nginx to look for files inside the /var/www/example.com directory to serve incoming HTTP GET requests. With this configuration, Nginx will map requests made to:

  • http://example.com/images/logo.png into the file path /var/www/example.com/images/logo.png.
  • http://example.com/contact.html into the file path /var/www/example.com/contact.html
  • http://example.com/about/us.html into the file path /var/www/example.com/about/us.html

What does the index directive tells Nginx?

The index directive tells Nginx that whenever a HTTP GET request is made to a directory inside the directory specified by the root directive, it should attempt to serve the index.html file from that directory. For this configuration, Nginx will map requests made to:

  • http://example.com/ into the file path /var/www/example.com/index.html.
  • http://example.com/about into the file path /var/www/example.com/about/index.html, if /var/www/example.com/about is a directory on the server's file system.

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.