Nginx reverse proxy rewrite URL

need

        The nginx server proxies the front-end items and reverses the back-end servers. There is no problem when using it during development. After deployment, there is the same request for the root address. Enter the nginx address localhost:3000 to access the front-end address, but an error will appear when calling the back-end interface. It seems that I do not know enough about nginx , It is found that when calling the back-end interface, there will be more /api/ in each request , but the back-end interface path does not have this /api/, and finally solve the problem by rewriting the url.

General reverse proxy

Generally, a unified prefix is ​​defined, such as: api, and the configuration is as follows

server {
    listen              80;
    server_name         default;
    
    location /api/ {
        proxy_set_header Host $host;
        proxy_set_header  X-Real-IP        $remote_addr;
        proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://example.com;
    }
}

Then when the request goes to  http:localhost/api/findOne , it will be forwarded to  http://example.com/api/findOne.

Just set proxy_pass . The request will only replace the domain name, not /api/.

Now I want to visit http:localhost/api/findOne and forward it to http://example.com/findOne. If /api/ is removed, the following two configurations can be followed.

 Option 1 uses rewrite , notice that there is no proxy_pass at the end  /, rewrite rewrites the url, and the final request is http://example.com/findOne

server {
  listen              80;
  server_name         default;
    
  location /api/ {
      proxy_set_header Host $host;
      proxy_set_header  X-Real-IP        $remote_addr;
      proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
      proxy_set_header X-NginX-Proxy true;

      rewrite ^/api/(.*)$ /$1 break;
      proxy_pass http://example.com;
  }
}

For the usage of rewrite, please refer to: nginx address rewriting, reverse proxy_Xiao Xiaoyan's Marshmallow Blog-CSDN Blog 

  • Solution 2 Add / after proxy_pass, then nginx will splice the content after /api to proxy_pass.

server {
  listen              80;
  server_name         default;
    
  location /api/ {
      proxy_set_header Host $host;
      proxy_set_header  X-Real-IP        $remote_addr;
      proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
      proxy_set_header X-NginX-Proxy true;

      proxy_pass http://example.com/;
  }
}

Guess you like

Origin blog.csdn.net/m0_64210833/article/details/130481374