The Difference Between Nginx Reverse Proxy proxy_pass Target Address with and without /

Publish: 2022-12-03 | Modify: 2022-12-03

proxy_pass is a commonly used directive in Nginx reverse proxy. There is a small detail (pitfall) with this directive that you may have encountered if you have used it. Sometimes, it may seem logically correct, but you may encounter 4xx or 5xx errors when accessing the server. The presence or absence of a trailing / in the target address of proxy_pass makes a difference. Let's take a look at it together.

Example

Suppose the address I am accessing is http://domain.com/test/api, and there is the following reverse proxy configuration:

location ^~ /test/ {
      # Target path with /
      proxy_pass https://192.168.2.6/;
}

As you can see, the target address of the reverse proxy is https://192.168.2.6/ with a trailing /. When accessing http://domain.com/test/api, it will ultimately reach the source server at https://192.168.2.6/api.

Suppose the target address is https://192.168.2.6 without a trailing /, the configuration would be:

location ^~ /test/ {
      # Target path without /
      proxy_pass https://192.168.2.6;
}

When accessing http://domain.com/test/api, the final request will reach the source server at https://192.168.2.6/test/api. Therefore, the paths to request the source server are different in these two cases. You need to determine whether the proxy_pass target path should have a trailing / based on your own business. If you are not clear about this rule, you may encounter issues for a long time.

Summary

  • proxy_pass target path with /: In this case, the path in the location directive will not be appended to the target path.
  • proxy_pass target path without /: In this case, the path in the location directive will be appended to the target path before being passed to the source server.

This article partially refers to: Nginx 增加二级目录的反向代理时,最常见的两个问题


Comments