为什么我的nginx“重写”指令导致重定向循环?

时间:2016-01-18 11:47:45

标签: nginx openresty nginx-location

给定以下http块,nginx按预期执行。也就是说,它会将http://localhost/3ba48599-8be8-4326-8bd0-1ac6591c2041/等网址重写为http://localhost/modif/3ba48599-8be8-4326-8bd0-1ac6591c2041/并将其传递给uwsgi服务器。

http {    
    upstream frontend {
        server frontend:8000;
    }

    server {
        listen 8000;
        server_name localhost;

        root /www/;

        location ~* "^/([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})/?$" {
            include uwsgi_params;
            set $uuid $1;
            if ($cookie_admin) {
              # if cookie exists, rewrite /<uuid> to /modif/<uuid> and pass to uwsgi
              rewrite / /modif/$uuid break;
              uwsgi_pass frontend;
            }
            content_by_lua_block {
                ngx.say("Ping!  You got here because you have no cookies!")
            }
        }
    }
}

然而,当我按照显示的方式添加另一个location块时,事情会变得轻松,我会得到ERR_TOO_MANY_REDIRECTS

http {
    # access_log /dev/stdout;  # so we can `docker log` it.

    upstream frontend {
        server frontend:8000;
    }

    server {
        listen 8000;
        server_name localhost;

        root /www/;

        location / {  # THIS MAKES EVERYTHING FALL APART :(
            uwsgi_pass frontend;
            include uwsgi_params;
        }

        location ~* "^/([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})/?$" {
            include uwsgi_params;
            set $uuid $1;
            if ($cookie_admin) {
              # if cookie exists, rewrite /<uuid> to /modif/<uuid> and pass to uwsgi
              rewrite / /modif/$uuid break;
              uwsgi_pass frontend;
            }
            content_by_lua_block {
                ngx.say("Ping!  You got here because you have no cookies!")
            }
        }
    }
}

这里到底发生了什么?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我看到你的Nginx正在侦听端口8000,但你的上游服务器位于'前端',也是在端口8000上。如果frontend解析为运行Nginx的同一台服务器,那么你已经得到了发生代理请求的循环。