ruby - 如何让 nginx 返回静态响应并将请求 header 发送到应用程序?

标签 ruby nginx rack high-load

我正在通过嵌入制作一个高负载的网络统计系统<img>标记到站点。我想做的是:

  1. nginx 从某个主机获取图像请求
  2. 它给出了从文件系统托管小的 1px 静态图像的答案
  3. 此时它以某种方式将请求的 header 传输到应用程序并关闭与主机的连接

我正在使用 Ruby,我打算制作一个纯 Rack 应用程序来获取 header 并将它们放入队列中以供进一步计算。

我无法解决的问题是,如何配置 sphinx 为 Rack 应用程序提供 header ,并在不等待 Rack 应用程序响应的情况下返回静态图像作为回复?

此外,如果有更常见的 Ruby 解决方案,则不需要 Rack。

最佳答案

一个简单的选择是在继续后端进程的同时尽快终止客户端连接。

server {
    location /test {
        # map 402 error to backend named location
        error_page 402 = @backend;

        # pass request to backend
        return 402;
    }

    location @backend {
        # close client connection after 1 second
        # Not bothering with sending gif
        send_timeout 1;

        # Pass the request to the backend.
        proxy_pass http://127.0.0.1:8080;
    }
}

上述选项虽然简单,但可能会导致客户端在连接断开时收到一条错误消息。 ngx.say 指令将确保发送“200 OK” header ,并且因为它是异步调用,所以不会拖延。这需要 ngx_lua 模块。

server {
    location /test {
        content_by_lua '
            -- send a dot to the user and transfer request to backend
            -- ngx.say is an async call so processing continues after without waiting
            ngx.say(".")
            res = ngx.location.capture("/backend")

        ';
    }

    location /backend {
        # named locations not allowed for ngx.location.capture
        # needs "internal" if not to be public
        internal;

        # Pass the request to the backend.
        proxy_pass http://127.0.0.1:8080;
    }

}

一个更简洁的基于 Lua 的选项:

server {
    location /test {
        rewrite_by_lua '
            -- send a dot to the user
            ngx.say(".")

            -- exit rewrite_by_lua and continue the normal event loop
            ngx.exit(ngx.OK)
        ';
        proxy_pass http://127.0.0.1:8080;
    }
}

绝对是一个有趣的挑战。

关于ruby - 如何让 nginx 返回静态响应并将请求 header 发送到应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8374085/

相关文章:

ruby - 西纳特拉:三个日志

ruby-on-rails - Rails fixtures 魔法柱不再起作用

ruby - REXML - 如何提取单个元素

django - 被 CORS 策略阻止 - 从 Django 应用程序访问 S3 存储桶

swift - iOS 12 wkwebview 无法使用重定向?

ruby-on-rails - rails : losing quotes in post parameters

ruby - 如何解决 PATH 中的 Insecure world writable dir/usr,Ruby 模式 040777 警告?

ruby-on-rails - sqlite3_native.so : [BUG] Segmentation fault

django - socks 的 Gunicorn 和 Django 错误权限被拒绝

ruby-on-rails - rvm rack ruby​​ 错误已经初始化常量 WFKV_