Understanding the Difference Between Trailing Slash and No Slash in Nginx proxy_pass

nginx proxy_passtrailing slashreverse proxy configurationnginx locationurl rewriting
Published·Modified·

proxy_pass is a common directive used in Nginx reverse proxy configurations. There is a subtle detail (a common pitfall) associated with it that users may encounter: sometimes the logic appears correct, but accessing the site results in 4xx or 5xx errors. The meaning of the target address in proxy_pass differs depending on whether it ends with a / or not. Let's take a closer look.

Nginx 520 Error

Example

Suppose you are accessing the address http://domain.com/test/api, and you have the following reverse proxy configuration:

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

Here, the reverse proxy target address is https://192.168.2.6/, which ends with a /. When accessing http://domain.com/test/api, the request will ultimately reach the origin server at https://192.168.2.6/api.

If the target address is https://192.168.2.6 without a trailing slash, the configuration would look like this:

location ^~ /test/ {
      # Target path does not include /
      proxy_pass https://192.168.2.6;
}

When accessing http://domain.com/test/api, the final request will reach the origin server at https://192.168.2.6/test/api. Therefore, the path used to request the origin server is different in both cases. You need to determine whether the proxy_pass target path should include a / based on your specific business logic. If you are unclear about this rule, you may encounter issues for a long time.

Summary

  • proxy_pass target path includes /: The path in the location block will not be appended to the target path.
  • proxy_pass target path does not include /: The path in the location block will be appended to the target path before being passed to the origin server.

This article references content from: Two Most Common Problems When Adding Secondary Directory Reverse Proxy in Nginx