An error is reported when an HTML page cross-domain requests image resources: Failed to load resource: the server responded with a status of 403 (Forbidden)

       The author has just completed a Spring boot project recently. The index.html page element <img> on the home page refers to the image link of the third-party server. Enter http://localhost or http://127.0.0.1 in the local test environment to open the home page, and the image The display is normal, and it is also displayed normally if you directly enter the image path in the browser.

<img class="banner-image" src="http://img.xxx.cn/image/056ef627a026b86c45be1ce0bb12df5b.jpeg" width="100%" />

       But after the project is packaged and released to the server, after the browser enters the homepage path of the site, a large blank box appears in the image display area of ​​the page, so I check the browser console and find an error: Failed to load resource: the server responded with a status of 403 (Forbidden).

       After consulting the relevant content, I learned that this is caused by the server's strategy to prevent hotlinking. Generally speaking, downloading image resources from a server site will incur related traffic charges (such as Alibaba Cloud's oss server), so some methods are needed to prevent similar hotlinking from happening. The principle behind it is to use the referrer header of the http request Information, the referer in the headers indicates which site (domain name) you came from to the server where the image resource is located. When we request the page, we can also see the specific content of the referrer header information through the packet capture software. Generally speaking It is the domain name of your own site.

       The content of the referrer can be obtained on the server side and processed according to the needs. For example, if the content of the referrer is empty or in the whitelist, no anti-leech processing will be performed. Otherwise, it will prompt 403 Forbidden. There is currently a simple solution The solution to this problem: add meta attributes to our HTML pages:

<meta name="referrer" content="no-referrer" />

       After this processing, when our page requests image resources from a third-party server, the referrer header information of the header will be empty. If the third-party site allows resource requests with an empty referrer, then we can request image resources normally.

Reference: Referrer strategy and meta tag issues

Guess you like

Origin blog.csdn.net/crazestone0614/article/details/126639645