Ad

HTML Served From Nginx Does Not Display Images

- 1 answer

I am having an issue with Nginx configuration. I have enabled proxy_intercept_errors and created rewrite rules to display a particular HTML page from the server directory in case if one of the 404, 502, 503 error occurs. I have tested these error codes and they are intercepted correctly and the necessary HTML page with text is displayed. But the issue is that these images somehow are not displayed in my custom HTML page. Maybe there is something wrong with file paths or Nginx configuration.

HTML file location on the server:

/var/www/html/

Images location:

/var/www/html/images/

For these aforementioned directories I have set chmod 755, but for files chmod 644

Nginx settings:

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 file content:

<!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>

When I change location in Nginx directly to the image files, then they are served and displayed correctly. Problem with images not displaying only appears when html file is served.

Ad

Answer

You need to tell Nginx how to handle the /images/404.jpg URL. It does not know that it came from a previous error_page 404 exception. The request to the URL that caused the error_page 404 exception and the request to the URL for the image are essentially independent of each other.

Assuming that localhost:8080 never needs to see any URL that begins with /images/, just add a simple location block:

location /images/ {}

It will use the value of root defined in the outer block.

If localhost:8080 needs to see some URLs that begin with /images/, use a more specific rule:

location = /images/404.jpg {}
location = /images/502.jpg {}
location = /images/503.jpg {}
Ad
source: stackoverflow.com
Ad