Nginx : Configuration : Serving Static contents ( Images / Static HTML / Assets )

This page is continuity of my last post Linux Distributions : Nginx : Configuration Basics

After you install Nginx inside the folder  /etc/nginx/ you can see the file nginx.conf which has a working configuration and some commented directives. Don’t change anything if you are beginner.

Inside the folder /etc/nginx/sites-enabled/ you see a file named default. copy this file using the command $ sudo cp default localhost.conf. This file now will have configuration related to your site. If you want to maintain another site on this computer/server then you can add another copy of the file default.
Note: If you don’t want to delete the default template then you need to make a little modification in /etc/nginx/nginx.conf. change the line ( line number around 71/72)

include /etc/nginx/sites-enabled/*;


include /etc/nginx/sites-enabled/*.conf;

An important web server task is serving out files (such as images or static HTML pages). You will implement an example where, depending on the request, files will be served from different local directories: /data/www(which may contain HTML files) and /data/images (containing images). This will require editing of the configuration file and setting up of a server block inside the http block with two location blocks.

First, create the /data/www directory and put an index.html file with any text content into it and create the/data/images directory and place some images in it.

Next, open the configuration file /etc/nginx/sites-enabled/localhost.conf. The default configuration file already includes several examples of the server block, mostly commented out. For now comment out all such blocks and start a new server block:

# Make sure your server block has following codes
 root /data/www; 
 location / {
   # First attempt to serve request as file, then
   # as directory, then fall back to displaying a 404.
   try_files $uri $uri/ =404;
   # Uncomment to enable naxsi on this location
   # include /etc/nginx/naxsi.rules
 # serve all the image files from /data/images/
 location ~* \.(png|jpg|jpeg)$ {
   root /data/images/;


One thought on “Nginx : Configuration : Serving Static contents ( Images / Static HTML / Assets )

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s