【问题标题】:How to serve static files like javascript css images and pdfs in production environment django+static+nginx如何在生产环境django+static+nginx中提供静态文件,如javascript css图像和pdf
【发布时间】:2019-07-15 18:16:41
【问题描述】:

1.我的环境是Redhat 7,Django 2.2,nginx版本:nginx/1.15.12。 我有两个静态位置,我需要在两个时间都得到服务。同一服务器上的第一个位置和第二个位置是安装的网络驱动器,用于存储图像和所有其他 pdf。

有两个问题。 1. 如何为两个静态位置提供服务。 这两个位置是 a)/www/AutomationServices/静态 b)/storage/Investigator_Validator。 在 nginx conf 我试过了

 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;
        }

我在 /storage/Investigator_Validator 下有多个文件夹。在每个子文件夹中都有根据其分类分组的 pdf、图像和文本文件。当我试图为他们服务时,它不起作用。但是当我尝试 python manage.py collectstatic 时,/storage/Investigator_Validator 中的文件夹和文件被复制到这个文件夹/www/AutomationServices/static 中。它当时有效,但 /storage/Investigator_Validator 中的文件动态变化,因此每次创建这些图像时运行 python manage.py collectstatic 并不好。

需要使用 nginx 网络服务器提供两个静态位置。如何使用 nginx 在文件夹中搜索 js、css、images 文件的子文件夹。

【问题讨论】:

    标签: nginx static production-environment django-2.2


    【解决方案1】:

    所以 URI /static/foo/bar.css 可以在 /www/AutomationServices/static/foo/bar.css/storage/Investigator_Validator/foo/bar.css 中找到。后者不包括 /static/ 作为路径名的一部分。

    有很多方法可以实现这一点,一种是使用 正则表达式 location 来捕获 URI 的尾部。 root 设置为公共根目录(在本例中为/),try_files 用于依次测试每个路径。

    例如:

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

    【讨论】:

    • 我应该删除这个代码位置/static/ { autoindex on; root /www/AutomationServices/static; try_files $uri $uri/ @secondStatic; } location /storage/ { root /storage/Investigator_Validator; } location @secondStatic{ root /storage/Investigator_Validator; }
    • Not Found: /static/GS-US-419-4015/volfova-miroslava-20171206-419-4015-1572.png [pid: 15750|app: 0|req: 4/7] 10.20.89.127 () {46 vars in 960 bytes} [Mon Jul 15 20:05:56 2019] GET /static/GS-US-419-4015/volfova-miroslava-20171206-419-4015-1572.png => generated 1933 bytes in 4 msecs (HTTP/1.1 404) 5 headers in 168 bytes (1 switches on core 0) 仍然没有找到。我删除了所有静态位置,只是提出了你给出的建议,但是 js 和 css 是从第一个位置工作的,而不是从第二个位置工作的。
    • 该文件的路径名是什么?
    • 该文件的实际路径是/storage/Investigator_Validator/GS-US-419-4015/volfova-miroslava-20171206-419-4015-1572.png,静态应该是/static/GS-US-419-4015/volfova-miroslava-20171206-419-4015-1572.png
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    • 2017-12-30
    • 2018-09-25
    相关资源
    最近更新 更多