nginx custom error page 502 with css and image files

后端 未结 3 586
执笔经年
执笔经年 2021-01-05 01:26

I\'m trying to add a custom error page for 503. I added these lines to server conf in nginx.conf file:

error_page 500 502 503 504 /50x.html;
location = /50x.h         


        
相关标签:
3条回答
  • 2021-01-05 02:08

    I just had the same problem, and what did work is setting the nginx conf like this :

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
      root  /home/username/sites/myProject/current/errorPages;
    }
    location = /image.png {
      root /home/username/sites/myProject/current/errorPages/50x_files;
    }
    

    And then reference the image simply as src="image.png". The same should apply to your css and js!

    Edit : I find a way to make it work for a bunch of file:

    error_page 500 502 503 504 /errorPages/50x.html;
    location /errorPages/ {
      root  /home/username/sites/myProject/current/;
    }
    

    This way all the files in the errorPages folder will be available (e.g. src="/errorPages/image.png"), as nginx will try to match all "/errorPages/...". It is necessary to remove both the "=" after "location" (as it's not an exact match anymore) and the "internal;" in it (as the other resources will be called from the html and not internally by nginx).

    0 讨论(0)
  • 2021-01-05 02:10

    I think the best approach is to do the following things:

    • Use inline CSS
    • Convert your images to Base64

    After doing this, you can embed the generated Base64 string into the background-image CSS rule as follows:

    background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEADI.....==)
    

    You can use the string with the <img> tags as well, just pass it to the src attribute as follows:

    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEADI.....==" />
    

    This way you can keep the internal nginx rule.

    0 讨论(0)
  • 2021-01-05 02:13

    The reason that your image/css is not shown/loaded, is because you're using the internal directive. The internal directive specifies that a given location can only be used for internal requests, and is not available or accessible from the outside (i.e. http://mysite/errorPages/500.html). Thus, a 404 error on its turn is given for these files.

    A few workarounds are:

    1. Remove the internal directive

      error_page 500 502 503 504 /50x.html;
      location = /50x.html {
          root  /home/username/sites/myProject/current/errorPages;
      }
      
    2. Use css inline styles for your error pages. This however won't work for your images, or other files that are linked to your page.
    3. Place the css and image files outside of the errorPages folder, and refer to them in your html code, with a relative path, starting from the root of your website.
    0 讨论(0)
提交回复
热议问题