HAProxy – Regular Expression to Restrict URL

haproxyregex

I had successfully restricted an URL in my web app to certain trusted IP, using below-mentioned config in haproxy config

acl trusted-ip src -f /etc/haproxy/whitelist.lst    
acl protected-page url /abc /abc/    
acl allowed-page url /abc/api/
http-request deny if protected-page !allowed-page !trusted-ip

I want all users to access "/abc/api" URL, while "/abc" will be accessible only to Trusted IP.
The problem here is if anyone from non-trusted IP enters "/abc?something" the URL "/abc" opens, in order to avoid this, I modified the config to

acl trusted-ip src -f /etc/haproxy/whitelist.lst
acl protected-page url_reg ^(?!\/abc\/api).*$
http-request deny if protected-page !trusted-ip

Now I was able to solve the above-mentioned problem, but the "/abc/api" is not accessible to anyone. Any help will be appreciated.

Best Answer

Use path instead of url

This extracts the request's URL path, which starts at the first slash and ends before the question mark (without the host part). A typical use is with prefetch-capable caches, and with portals which need to aggregate multiple information from databases and keep them in caches. Note that with outgoing caches, it would be wiser to use "url" instead. With ACLs, it's typically used to match exact file names (eg: "/login.php"), or directory parts using the derivative forms. See also the "url" and "base" fetch methods.

ACL derivatives :
  path     : exact string match
  path_beg : prefix match
  path_dir : subdir match
  path_dom : domain match
  path_end : suffix match
  path_len : length match
  path_reg : regex match
  path_sub : substring match