user222213
user222213

Reputation: 111

How to serve static files like javascript css images and pdfs in production environment django+static+nginx

1.My environment is Redhat 7, Django 2.2, nginx version: nginx/1.15.12. I have two static locations and I need to be served at both times. The first location in on the same server and second location is a mounted network drive where store images and all other pdfs.

There are two problems. 1. How to serve both static locations. The two locations are a)/www/AutomationServices/static b)/storage/Investigator_Validator. In nginx conf i tried

 location /static/ {
        autoindex on;
        root /www/AutomationServices/static;
       try_files $uri $uri/  @secondStatic;
    }
    location /storage/ {
        root /storage/Investigator_Validator;
    }
    location @secondStatic{
        root /storage/Investigator_Validator;
        }

I have multiple folders under /storage/Investigator_Validator. In each subfolder there are pdfs,images and text files grouped according to their classification. When I tried to serve them its not working. But When I tried python manage.py collectstatic the folders and files in the /storage/Investigator_Validator are copied to this folder /www/AutomationServices/static. It worked that time but the files in /storage/Investigator_Validator changes dynamically so its not good to run python manage.py collectstatic everytime when i create those images.

Need to serve two static locations using nginx webserver. How to search subfolders in folders for js,css,images files using nginx.

Upvotes: 1

Views: 88

Answers (1)

Richard Smith
Richard Smith

Reputation: 49672

So the URI /static/foo/bar.css may be found in /www/AutomationServices/static/foo/bar.css or /storage/Investigator_Validator/foo/bar.css. The latter not including /static/ as part of the pathname.

There are a number of ways to achieve this, one being to use a regular expression location to capture the tail end of the URI. The root is set to a common root directory (in this case /) and try_files is used to test each path in turn.

For example:

location ~ ^/static/(.*)$ {
    root /;
    try_files /www/AutomationServices/static/$1 /storage/Investigator_Validator/$1 =404;
}

Upvotes: 1

Related Questions