nginx serve static files from different location

How to Serve Static Files from Different Folder in NGINX

Sometimes you may need to serve static files from different subdirectory. In this article, we will look at how to serve static files from different folder in NGINX.


How to Serve Static Files from Different Folder in NGINX

Here are the steps to serve static files from different folder in NGINX.


1. Open NGINX Configuration file

Open terminal and run the following command to open NGINX configuration file.

$ sudo vi /etc/nginx/nginx.conf


2. Change Static File Location

Look for the location block that serves static files e.g. /static/

location /static/ {
...
}

Update its root directive to point to the parent folder of static files. For example, if your static files are located at /var/www/html/static, then add the following root directive

root /var/www/html

So your location block will look like

location /static/ {
  root /var/www/html;
}

Please note, if you use root directive, NGINX will append the location name /static to all paths. For example, if you request /static/image.jpg, then NGINX will look for it in /var/www/html/static/image.jpg.

If you want to use a different folder for serving static files or if you don’t want NGINX to append location name /static/ after root location, use alias directive instead of using root. For example, if your static files are located at /var/www/html/static_files and you want to serve them from /static/ URLs, then use the following alias directive.

alias /var/www/html/static_files

So your location block will look like

location /static/ {
  alias /var/www/html/static_files/;
}

Please remember to add trailing slash at the end of Alias directive as shown above. Now when a user requests /static/image.jpg file, NGINX will look for /var/www/html/static_files/image.jpg.


3. Restart NGINX server

Restart NGINX server to apply changes.

$ sudo service nginx restart

In this article, we have looked at how serve static files in NGINX from different locations.

Also read:

How to Pass Parameters to Shell Script Functions
How to Force NGINX to Serve New Static Files
How to Return Value in Shell Script
How to Retrieve POST request data in Django
How to Temporarily Disable Foreign Key Constraint in MySQL