nginx proxy static resource returns 404 problem solving process

The cause of the problem is that the system is deployed in a cluster of two servers, and the video analysis program is running at the same time. The pictures in the video will be intercepted and provided for front-end access. However, the pictures intercepted by the two servers cannot be shared, so I thought of using nginx to make a static resource sharing. acting. Mainly use try_files configuration to retrieve local files. If not, proxy to another server. The problem is that server A does not have the image and will proxy to server B. B also receives the proxy request and the image also exists, but it keeps returning. 404, and then request B directly through the url to get the image. A’s nginx configuration is as follows

 

 

 The configuration of B is as follows

There is no problem with the configuration. The nginx services of A and B can be started. Let me first talk about my troubleshooting ideas and finally the reasons and solutions.

The first thing I thought of was the path problem. I compared the paths of proxy requests and direct requests through nginx logs and found that the paths were the same. I ruled out path problems.

 Then I considered the restrictions on the proxy_pass keyword, so I changed to rewrite. However, rewrite has a problem. It will return 304 to the browser, and the browser will make a redirect request. This will expose the address of the static resource, which is not safe, so give up.

Next, I considered that the proxy configuration might be wrong, so I removed try_files and performed the proxy directly in the static block. I found that it didn't work either. It was the same as the error at the beginning. It was now a deadlock. Later, I finally solved the problem by checking the information.

In fact, the main reason lies in the host attribute in the http request. We know that nginx needs to listen to the server_name and port, and perform proxying based on the requested server_name and port. In fact, the server_name is not matched based on the requested address, but based on the host attribute in the request. Matching, when we configure the proxy, the default proxy host configuration of nginx is like this

proxy_set_header Host $proxy_host;

This is actually the backend address of the request. When we set the upstream, $proxy_host is the name of the upstream, so A receives the request first and then forwards it. Since the upstream I set is fileserver, the host of the request received by B is fileserver, and the server_name monitored by B is the address of B, so it cannot match the server_name and always returns 404.

Then I set the Host to be the address of B when A forwards, and the proxy can work normally.

 

Guess you like

Origin blog.csdn.net/weixin_45087884/article/details/131312048