问题
I have a situation where I have part of a website (certain URL paths) being served from one backend server while all other URLs are being served from a different default backend in HAProxy.
Now, because of the way the application logic was written, the files to be served under the same URL path could be created at the same path on either of the two physical server machines. I would like to be able to serve these files regardless of which machine the file exists on. So in a nutshell, how can I forward the request to one backend and if the response is a 404 (the file does not exist there), forward the request to be served from the other backend?
I am a complete noob to HAProxy so any help will be appreciated. Thanks.
The relevant portions of my haproxy.conf
:
frontend frontend0
...
acl de path_beg /path1
acl de path_beg /path2
acl de path_beg /path3
use backend backend1 if de
default_backend bakend
backend backend1
...
server server_name 127.0.0.1:8000
backend backend2
...
server server_name 192.168.11.1:8000
There is a path /path4
that needs to be served from both of these machines depending on where the file exists.
回答1:
Thanks to @Michael-sqlbot for the hint and this question on ServerFault for the outline of the answer. The setup I finally ended up using is as follows:
- I setup a separate URL /_path4 that is served from one backend while the original URL /path4 is served from the other backend.
- On receiving a 404 response from the first backend for /path4, I redirect to the URL /_path4
My configuration file now looks as follows:
frontend frontend0
...
acl de path_beg /path1
acl de path_beg /path2
acl de path_beg /path3
acl de path_beg /_path4
use_backend backend2 if de
default_backend backend1
...
backend backend1
...
http-request set-var(txn.path) path
server server_name 127.0.0.1:8000
http-response redirect location %[var(txn.path),regsub('^/path4','/_path4')] code 303 if { status 404 } { var(txn.path) -m beg '/path4' }
...
backend backend2
...
server server_name 192.168.11.1:8000
As explained in @Michael-sqlbot's excellent comments to the linked question, the setting of a transaction variable is required because at the http-response
stage, the buffer has been released and so the normal path
variable used in the frontend is not available.
来源:https://stackoverflow.com/questions/50687558/haproxy-serving-a-url-from-2nd-machine-if-the-1st-returns-a-404