HTML 从 Nginx 提供的服务不显示图像

HTML served from Nginx does not display images

我遇到 Nginx 配置问题。我启用了 proxy_intercept_errors 并创建了重写规则以显示服务器目录中的特定 HTML 页面,以防出现 404、502、503 错误之一。我已经测试了这些错误代码,它们被正确拦截,并显示了必要的 HTML 页面和文本。但问题是这些图像不知何故没有显示在我的自定义 HTML 页面中。可能文件路径或Nginx配置有问题。

HTML 服务器上的文件位置:

/var/www/html/

图片位置:

/var/www/html/images/

对于上述这些目录,我设置了 chmod 755,但是对于文件,我设置了 chmod 644

Nginx 设置:

server {
    listen 443 ssl http2;
    server_name example.net;

    proxy_intercept_errors on;
    root /var/www/html;
    error_page 404 @404;
    error_page 502 @502;
    error_page 503 @503;

    access_log      /var/log/nginx/example.net.ssl.access.log;
    error_log       /var/log/nginx/example.net.ssl.error.log;

    ssl_certificate         /etc/letsencrypt/live/example.net/cert.pem;
    ssl_certificate_key     /etc/letsencrypt/live/example.net/privkey.pem;

    location / {
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://localhost:8080;
    }

    location @404 {
      rewrite ^(.*)$ /404.html break;
    }

    location @502 {
      rewrite ^(.*)$ /502.html break;
    }

    location @503 {
      rewrite ^(.*)$ /503.html break;
    }

HTML文件内容:

<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<title>404</title>
<style>
img {
  display: block;
  margin-left: auto;
  margin-right: auto;
}
</style>
<body>
   <img src="/var/www/html/images/404.jpg" alt="404 Not Found" style="width:50%;">
</body>
</html>

当我将 Nginx 中的位置直接更改为图像文件时,它们会被正确提供和显示。图像不显示问题仅在提供 html 文件时出现。

你需要告诉Nginx如何处理/images/404.jpgURL。它不知道它来自先前的 error_page 404 异常。导致error_page 404异常的对URL的请求和对URL图片的请求本质上是相互独立的。

假设 localhost:8080 永远不需要看到任何以 /images/ 开头的 URL,只需添加一个简单的 location 块:

location /images/ {}

它将使用在外部块中定义的 root 的值。

如果 localhost:8080 需要查看某些以 /images/ 开头的 URL,请使用更具体的规则:

location = /images/404.jpg {}
location = /images/502.jpg {}
location = /images/503.jpg {}