当 nginx 中不存在文件时默认为 404

Defaulting to 404 when file doesn't exist in nginx

这是我的 nginx 设置:

location / {
    root /var/www/web-app/public;
    index index.html index.htm;
    try_files $uri $uri/ /index.html;
    default_type "text/html";
}

location /profile_images {
    try_files $uri $uri/ =404;
}

问题在第二个街区。这是一个充满图像的目录。当我根据用户 ID 查找图像时,我可能有也可能没有图像。如果没有,我想要一个 404 错误。基于以上内容,我现在在所有图像上都得到了 404。 404=404.

我都试过了

第一个位置是我的 api,效果很好。

我用 src='/profiles_images/***.png'

查找图像(在 html 中)

为了它的价值,我正在使用 reactjs。

您缺少第二个 location 块的 root 指令。如果几个 location 块共享 root 的相同值,通常的做法是将 root 语句放在封闭的 server 块中,以便所有 location 块继承相同的值。例如:

server {
    ...

    index index.html index.htm;
    root /var/www/web-app/public;

    location / {
        try_files $uri $uri/ /index.html;
    }

    location /profile_images {
        try_files $uri $uri/ =404;
    }
}

有关更多信息,请参阅 this document