使用 nginx proxy_pass 修改位置标头 [英] Modifying a Location header with nginx proxy_pass

查看:23
本文介绍了使用 nginx proxy_pass 修改位置标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 nginx proxy_pass 设置来将 /api 上的每个请求传递到后端 Tomcat REST 服务.此服务在某些情况下会返回一个 Location 标头,该标头根据请求的类型而变化,例如,Location: http://foo.bar/baz/api/search/1234567 -- baz 部分是因为它托管在 Tomcat 上.

I have an nginx proxy_pass setup to pass every request on /api through to a backend Tomcat REST service. This service in some cases returns a Location header which varies according to the type of request, e.g., Location: http://foo.bar/baz/api/search/1234567 -- the baz part is due to it being hosted on Tomcat.

我当前的配置正确地重写了 foo.bar 主机名,但保持 baz 部分完好无损.我想去掉这个,但 proxy_pass 选项似乎仅限于清除或设置标题的新值.

My current configuration rewrites the foo.bar host name correctly, but leaves the baz part intact. I'd like to strip this, but the proxy_pass options seem to be limited to clearing or setting a new value for the header.

有没有办法在传递给客户端之前动态修改标头,例如使用正则表达式替代?这是我的 nginx 配置:

Is there a way to modify headers dynamically before being passed on to the client, using a regex substitute, for instance? This is my nginx configuration:

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_max_temp_file_size 0;
    client_max_body_size    10m;
    client_body_buffer_size 128k;
    proxy_connect_timeout   90;
    proxy_send_timeout      90;
    proxy_read_timeout      90;
    proxy_buffers           32 4k;
    proxy_redirect off;

    proxy_pass http://foo.bar:8080/baz/api;
}

推荐答案

您也许可以使用正则表达式来修改它,但更好的方法是使用代理重定向:

You may be able to use regexp to modify it but a better way is to use a proxy redirect:

proxy_redirect http://foo.bar/baz/ /;

http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_redirect

foo.bar/baz/ 的任何位置标头都将转到 /

Any Location headers for foo.bar/baz/ will go to /

如果您只想重定向 /baz/api,那也可以.

If you just want to redirect /baz/api, that'll work too.

如果任何重定向也添加了端口,您还需要添加 http://foo.bar:8080/baz/(单独重定向).

If any redirects are also adding the port, you'll need to add http://foo.bar:8080/baz/ as well (separate redirect).

希望这有帮助!

这篇关于使用 nginx proxy_pass 修改位置标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆