简体   繁体   English

如何解决 nginx static 资产未找到错误

[英]how to resolve nginx static assets not found error

my application is working fine at我的应用程序运行良好

location / {
        include uwsgi_params;
        uwsgi_pass unix:/tmp/socket_file.sock;
}

but when i include static assets location location ~*.\(css|js|jpg|jpeg|gif|png|ico|zip|tgz|gz|rtf) it gives 404 not found error for css,js files但是当我包含 static assets location location ~*.\(css|js|jpg|jpeg|gif|png|ico|zip|tgz|gz|rtf)时,它会为 css,js 文件提供 404 not found 错误

server {
    listen 8080;
    server_name your_domain www.your_domain;
    location ~* \.(css|js|jpg|jpeg|gif|png|ico|zip|tgz|gz|rtf)$ {
       expires max;
       log_not_found off;
       access_log off;
    }

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/tmp/socket_file.sock;
    }
}

nginx error log show ` nginx 错误日志显示`

"/usr/share/nginx/html/static/js/jspdf.js" failed (2: No such file or directory) ' While my static assets are in /ProjectDirectory/assets/ “/usr/share/nginx/html/static/js/jspdf.js”失败(2:没有这样的文件或目录)'虽然我的 static 资产在 /ProjectDirectory/assets/

location s are mutually exclusive, ie only one may match at a time. location是互斥的,即一次只能匹配一个。 When the first location (regex) matches, directives in the second location / are ignored, and Nginx will proceed with whatever defined outside of this location block (if not defined).当第一个位置(正则表达式)匹配时,第二个位置/中的指令将被忽略,并且 Nginx 将继续执行此位置块之外定义的任何内容(如果未定义)。 In your case, it's apparent that root /usr/share/nginx/html is defined somewhere at an outer level.在您的情况下,很明显root /usr/share/nginx/html是在外层某处定义的。

A straightforward solution would be to add the same include and uwsgi_pass to the first location block, but since you're serving static files, why not let Nginx handle it by adding root /path/to/your/static/files ?一个简单的解决方案是将相同includeuwsgi_pass添加到第一个位置块,但是由于您正在提供 static 文件,为什么不让 Nginx 通过添加root /path/to/your/static/files处理它?

In practice, instead of matching file extension by regex, it's better to put all your files in one location, and use prefix-based matching:实际上,与其通过正则表达式匹配文件扩展名,不如将所有文件放在一个位置,并使用基于前缀的匹配:

location /static/ {
    alias /ProjectDirectory/assets/;
}

You might want to read this answer to learn about the differences between root and alias .您可能想阅读此答案以了解rootalias之间的区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM