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 and that are mapped to the IP address of the server where your Nginx installation is running from, and
  • the directory /var/www/ 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 {
    listen 80;
    root /var/www/;
    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 or 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/ directory to serve incoming HTTP GET requests. With this configuration, Nginx will map requests made to:

  • into the file path /var/www/
  • into the file path /var/www/
  • into the file path /var/www/

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:

  • into the file path /var/www/
  • into the file path /var/www/, if /var/www/ 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 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. Homepage 300x250 Domain names for just 88 cents!

Find a domain starting at $0.88

powered by Namecheap