0

below is my Nginx conf, I want to redirect my URL to another page if /api throws the error code is 502, How can I do it in nginx.

  location ~*/api {
    rewrite ^/api(.*) $1 break;
    proxy_pass http://127.0.0.1:3200;
    client_max_body_size 60M;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
  }
  location ~*/api/test {
    rewrite ^/api/test/(.*) /test/$1 break;
    proxy_pass http://127.0.0.1:3200;
    client_max_body_size 60M;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
  }

I have 2 locations 1) location ~/api 2/ location ~/api/test if the location ~/api gets 502 error i need to redirect to location ~/api/test

kirthan shetty
  • 491
  • 2
  • 5
  • 10

1 Answers1

0

You can use error_page directive.

location ~*/api {
    rewrite ^/api(.*) $1 break;
    proxy_pass http://127.0.0.1:3200;
    client_max_body_size 60M;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";

    error_page 502 @502;
}

If you want to write relative path. do like this,

location @502 {
    rewrite ^(*)/api(.*) $1/api/test;

    proxy_pass http://127.0.0.1:3200;
    client_max_body_size 60M;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
}
mariolu
  • 624
  • 8
  • 17
  • HI @mariolu, i have 2 locations 1) location ~*/api 2/ location ~*/api/test if the location ~*/api gets 502 error i need to redirect to location ~*/api/test – kirthan shetty Apr 07 '21 at 12:58