Nginx to serve static files

This article explains about , how to use nginx to serve static files and also gives you an example with configuration.

Hello all. Today we will see how to use nginx for static files serving (images, videos, files).

First of all how to get nginx on your machine

sudo apt-get install nginx

windows users for installation refer  here

Hope you are having a working nginx on your machine. To check nginx installed on your machine type
 nginx -v this shows version of the nginx installed like this  nginx version: nginx/1.11.0

Now we have to write the configuration file to nginx to serve static files.

The question is where to write?
     We need to understand the directory structure of nginx.

 nginx --|
              --- sites-enabled/
             --- sites-available/
              --- conf.d/
            --- lot-more-directories

we need to write the config in  sites-enabled/ directory.

But the best practice is to write config file in  sites-available and then create symbolic link to  sites-enabled.

Create one directory and Put some images inside static directory

 Open terminal and type the following command

 mkdir static

 cd static

Type  ls ->  1.jpg 2.jpg 3.png 4.jpg 5.jpg 6.jpg

under  static  directory i have 6 images inside in it .

server {
listen *:8881;

location /static {
alias /home/bala/static;

Here the  static directory is under  /home/bala/

In the example configuration server is running on port 8881.

Note: Make sure you replace  /home/bala/static with your directory path.

Now Put this config into  sites-available directory named  staticserve.conf

Create symbolic link by this command

 sudo ln -s /etc/nginx/sites-available/staticserve.conf /etc/nginx/sites-enabled/

Note: Always use absolute path . don’t use relative path like this
 sudo ln -s staticserve.conf /etc/nginx/sites-enabled/ — this will not work . Always use absolute path.

After creating symbolic link restart the nginx server.

In ubuntu 14.04 --->  sudo service nginx restart

In ubuntu 16.04 --->  sudo systemctl restart nginx.service

Now Open your favourite your browser and type this  http://localhost:8881/static/1.jpg

Now you will see  1.jpg opens in your favourite browser.

Now everything under  static directory is accessible in your browser by this link


If requested file not exists in the directory,  nginx will display default 404 page .

Thanks. Hope this helps. Happy Hacking!!!

Leave a comment

(Note: Comments are moderated)