Nginx server reverse proxy proxy_pass configuration method

  • 2020-05-10 23:30:18
  • OfStack

In the case of a normal reverse proxy
The configuration of Nginx is relatively simple, such as:


location ~ /* 
{
proxy_pass http://127.0.0.1:8008;
}

Or you can


location /
{
proxy_pass http://127.0.0.1:8008;
}

The reverse proxy configuration of Apache2 is:


ProxyPass /ysz/ http://localhost:8080/

However, if you want to configure a relatively complex reverse proxy
Nginx is a little bit more trouble than Apache2
For example, a request starting with /wap/ in url is forwarded to a corresponding server in the background
You can set a variable in Nginx to temporarily save /wap/ path information


location ^~ /wap/
{
if ($request_uri ~ /wap/(\d+)/(.+))
{
set $bucketid $1;
set $params $2;
}
proxy_pass http://mx$bucketid.test.com:6601/$params;
}

You can also first rewrite1, and then proxy:


location ^~ /wap/{
rewrite /wap/(\d+)/(.+) /$2?$args break;
proxy_pass http://mx$1.test.com:6601;
}

or


location ~* /wap/(\d+)/(.+)
{
proxy_pass http://mx$1.test.com:6601/$2?$args;
}

Notice the last ? $args, indicating that the original url last get parameter is also given to the agent in the background
If you use a variable in proxy_pass (either the hostname variable $1 or the $2 variable that follows), you must add this code
However, if there is no variable after pass_proxy, then there is no need to add, it will send all url to the agent to the background by default, such as:


location ~* /wap/(\d+)/(.+)
{
proxy_pass http://mx.test.com:6601;
}

Apache2 is much simpler:


ProxyPassMatch ^/wap/(.*)$  http://192.168.132.147/$1
 
if ($host ~* www.(.*)){
      set $host_without_www $1;
      rewrite (.*)$ http://$host_without_www/www$1;
    }

url's/problem
When proxy_pass is configured in nginx, when url is added with /, it is equivalent to the absolute root path, then nginx will not proxy the part of the matching path in location. If there is no /, the agent is given the part of the path that matches.
 
The following 4 kinds of circumstances respectively with http: / / 192.168.1.4 proxy test. html for a visit.
1 species:


location /proxy/ {
     proxy_pass http://127.0.0.1:81/;
}

Is the agent to http: / / 127.0.0.1:81 / test. This url html
 
The second za (1 less/than the last one)


location /proxy/ {
     proxy_pass http://127.0.0.1:81;
}

Is the agent to http: / / 127.0.0.1:81 / proxy test. This url html
 
Third:


location /
{
proxy_pass http://127.0.0.1:8008;
}
0

Is the agent to http: / / 127.0.0.1:81 / ftlynx test. This url html.
 
Case 4 (1 less/in the end than case 3) :


location /
{
proxy_pass http://127.0.0.1:8008;
}
1

Is the agent to http: / / 127.0.0.1:81 / ftlynxtest. This url html
 
The above results are I combined with the log file test. As can be seen from the results, it should be divided into two cases. Namely http: / / 127.0.0.1:81 (2) above this and http: / / 127.0.0.1:81 /... (1,3,4 above) this one.


Related articles: