如何做基于自定义HTTP头的条件proxy_pass
假设我有4个nginx引擎运行在我的专用networking中,让我们调用它:web1,web2,web3,web4。
我有一个主要的nginx服务器,坐在互联网和我的私人networking,让我们打电话:Main_Web
在与Main_web相同的主机上,我在端口5000上运行基于python的身份validation服务,让callit auth_backend.py。
作为authentication后端,这个auth_backend.py将返回401,如果用户是回教徒。 但是对于合法用户,它将返回到内部位置(/ afterauth)的redirect(302),并且还添加自定义HTTP标题,
即: X-HTTP-BACKEND = 'http://web4/thispage?var=2'
/etc/nginx/conf.d/default
server { listen 80; server_name localhost; #charset koi8-r; #access_log /var/log/nginx/host.access.log main; add_header X-Backend $http_x_backend; location / { proxy_pass http://127.0.0.1:5000 ; proxy_set_header Host $host; } location /afterauth/ { set $my_next_proxy $upstream_http_x_backend; proxy_pass http://$my_next_proxy ; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } }
auth后端脚本
#!/usr/bin/python from flask import Flask, request, make_response, redirect app = Flask(__name__) @app.route('/',methods=['GET', 'POST']) def hello_world(): resp = make_response('Flask make_response', 200) #resp = redirect('afterauth/mykey=NEXTKEY') resp.headers['X-Backend']='192.168.100.1:5001/?key=MYKEY01' return resp if __name__ == "__main__": app.run(debug=True)
上次debugginghttps://pastebin.com/DwcgVeuN
在“最后的debugging”的114 – 126行,我得到了:
2017/10/13 03:22:53 [debug] 1737#1737: *9 http proxy header: "X-Backend: 192.168.100.1:5001/?key=MYKEY01" 2017/10/13 03:22:53 [debug] 1737#1737: *9 http proxy header: "Server: Werkzeug/0.12.2 Python/2.7.9" 2017/10/13 03:22:53 [debug] 1737#1737: *9 http proxy header: "Date: Thu, 12 Oct 2017 20:22:53 GMT" 2017/10/13 03:22:53 [debug] 1737#1737: *9 http proxy header done 2017/10/13 03:22:53 [debug] 1737#1737: *9 HTTP/1.1 302 FOUND Server: nginx/1.13.5 Date: Thu, 12 Oct 2017 20:22:53 GMT Content-Type: text/html; charset=utf-8 Content-Length: 253 Connection: keep-alive Location: http://192.168.100.48/afterauth/mykey=NEXTKEY X-Backend: 192.168.100.1:5001/?key=MYKEY01
如何把'192.168.100.1:5001/?key=MYKEY01'作为proxy_pass url?
诚挚
-bino-