How to Conditionally Set a Header Based on the Request Path in HAProxy
Question
In HAProxy, it’s not possible to directly use the request path in http-response rules because the HTTP request is no longer accessible once the response is being processed.
However, you can work around this by storing the path in a transaction-scoped variable during the request phase, and using that variable later in the response phase.
Objective is
Set a strict Cache-Control header:
no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0
only when the request path starts with /files/live/sites/mainsite/files/reports
Answer
HAProxy Configuration
http-request set-var(txn.path) path
acl is_reports_path var(txn.path) -m beg /files/live/sites/mainsite/files/reports
http-response set-header Cache-Control "no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0" if is_reports_path
Step-by-Step Explanation
-
Capture the path during the request phase
http-request set-var(txn.path) path
This saves the current request path (like /files/live/sites/mainsite/files/reports/2024/q2.pdf) into a transaction-scoped variable, accessible throughout the HTTP exchange.
-
Define an ACL to match the path prefix
acl is_reports_path var(txn.path) -m beg /files/live/sites/mainsite/files/reports
This matches any path that starts with the full string /files/live/sites/academy/files/reports
-
Set the Cache-Control header conditionally
http-response set-header Cache-Control "no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0" if is_reports_path
This prevents any caching of sensitive or frequently updated report files.