How to Serve Static Files using NGINX in 3 Simple Steps? ๐Ÿ’ก

How to Serve Static Files using NGINX in 3 Simple Steps? ๐Ÿ’ก


2 min read

NGINX has been the most popular web server for many years now, and it is used by a large number of websites and businesses around the world. NGINX is a very powerful tool and can be used to accomplish a lot of different tasks.

This blog will be about one of those various functions, and it will be about hosting static files on a server using NGINX.

Step 1: Editing the NGINX Config File

First of all, we'll have to edit the NGINX config file to add the directory, which will serve static content. Open the NGINX config file using the command:

sudo vi /etc/nginx/nginx.conf   # OR /etc/nginx/sites-enabled

Step 2: Updating the Location Block

Once you have opened the file using the vi editor, create a new location block in the server block.

server {
   server_name <>;
   location / {

   location /files/ {
      root /var/www;

In the above code snippet, we have added a new location block for the /files path and updated the root directive to point at /var/www. Now let's create an empty directory named /files on the above location.

Note: As we use the root directive in the location block, NGINX will add the route name to all paths. For example, if you request any file, NGINX will look it in the /var/www/files directory.

cd /var/www && mkdir files

Change the directory and create any file for testing purposes.

cd files
sudo touch hello.txt  # Add some random text too

Step 3: Restart the NGINX

Restart the NGINX server using the following command:

sudo service nginx restart

Test the NGINX configuration using sudo nginx -t to make sure there are no errors in the file.

Accessing the Static Files ๐Ÿš€

To access the files, you can simply visit the server URL with the route that is mentioned in the location block (/files)

curl <<Server_URL>>/files/<<file_name>>

If you liked this post or found it interesting, give it a thumbs-up ๐Ÿ‘

Thank you for reading! ๐Ÿ’ฏ

Did you find this article valuable?

Support Keshav Malik by becoming a sponsor. Any amount is appreciated!