Several Ways to Write and the Differences Between `server_name`, `location`, and `proxy_pass` in Nginx
This article provides an in-depth analysis of common configurations and potential pitfalls associated with the three core directives `server_name`, `location`, and `proxy_pass` in Nginx reverse proxy setups. First, `server_name` supports various matching methods, including exact domain names, wildcards, regular expressions, empty values, IP addresses, and variables. The matching priority is as follows: exact matches take precedence over prefix wildcards, which in turn take precedence over suffix wildcards and regular expressions. It is recommended to prioritize using wildcards for better performance. Second, the presence or absence of a trailing slash in `location` significantly affects matching behavior. For instance, `location /image` will match `/imageabc`, whereas `location /image/` only matches paths starting with `/image/`. Nginx follows the longest prefix matching principle, with `location /` serving as the fallback option. Finally, whether `proxy_pass` includes a trailing slash determines the path forwarding logic: if no path is specified, the original URI is preserved in its entirety; if a path is specified (including just a single slash), the prefix matched by `location` is replaced by the path specified in `proxy_pass`. This easily leads to incorrect forwarding paths. Understanding these subtle differences is crucial for correctly configuring Nginx and avoiding routing confusion.