How to do conditional proxy_pass based on custom HTTP Header
Suppose I have 4 nginx Engine run in my private network, lets Call it : web1, web2, web3, web4.
I have a main nginx server, sit betwen internet and my private network, lets call it : Main_Web
At the same host as Main_web, I have python based authentication service run on port 5000, lets callit auth_backend.py.
as an authentication backend this auth_backend.py will return 401 if user is ilegal. But for legal user it will return a redirect (302) to internal location (/afterauth) AND also add custom HTTP Header,
i.e: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 backend script
#!/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)
Last Debug at https://pastebin.com/DwcgVeuN
at line 114 - 126 of 'last debug', I got :
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
How to put that '192.168.100.1:5001/?key=MYKEY01' as proxy_pass url ?
Sincerely
-bino-
0 Answers