haproxy: restrict specific URLs to specific IP addresses

This snippet shows you how to use haproxy to restrict certain URLs to certain IP addresses. For example, to make sure your admin interface can only be accessed from your company IP address.

This snippet was tested on haproxy 1.5.

This snippet is tested on a Digital Ocean VPS. If you like this snippet and want to support me, plus get free credit @ DO, use this link to order a Digital Ocean VPS: https://www.digitalocean.com/?refcode=7435ae6b8212

This example restricts access to the /admin/ and /helpdesk URL’s. It only allows access from the IP addresses and Any other IP addresses will get the standard haproxy 403 forbidden error.

ACL for URL’s

It uses the acl option. If the requested path begins with either /admin or /helpdesk haproxy sets the restricted_page acl. haproxy also looks at the requesting source IP address. If that matches any of the two IP addresses, it sets the network_allowed acl. If the allowed_network acl is set and the restricted_page is also set, it allows a visitor to go to the page. If the restricted_page acl is set but the allowed_network is not, haproxy will serve a 403 error, thus, disallowing access to that specific URL.

Note that you can use IP addresses but also networks in the src acl. Both and work.

frontend example-frontend
  acl network_allowed src
  acl restricted_page path_beg /admin
  acl restricted_page path_beg /helpdesk
  block if restricted_page !network_allowed

To use a specific file as error page, use the following config in the defaults section:

  errorfile 400 /etc/haproxy/errors/400.http
  errorfile 403 /etc/haproxy/errors/403.http
  errorfile 408 /etc/haproxy/errors/408.http
  errorfile 500 /etc/haproxy/errors/500.http
  errorfile 502 /etc/haproxy/errors/502.http
  errorfile 503 /etc/haproxy/errors/503.http
  errorfile 504 /etc/haproxy/errors/504.http

The http files are regular HTML files with a HTTP response on top, like so:

  HTTP/1.0 403 Forbidden
  Cache-Control: no-cache
  Connection: close
  Content-Type: text/html
  <title>403 Forbidden</title>
  <p>You don't have permission to access this area
  on this server.</p>
  <address>Apache/2.4.12 (Ubuntu) Server at example.org Port 443</address>

This is the default apache error page.

ACL for TCP backends

** update 2017-01-09 **

If you have a non-http service you want to restrict to a few IP’s you can use an ACL together with the tcp-request connection reject optio. Here below is a simple example for a MySQL service. Do note that this also works in a frontend block:

listen mysql
      mode            tcp
      acl             network_allowed src
      tcp-request     connection reject if !network_allowed
      server          mysqlvip

More info on acl: http://cbonte.github.io/haproxy-dconv/configuration-1.5.html#acl
More info on errorfile: http://cbonte.github.io/haproxy-dconv/configuration-1.5.html#errorfile