HAProxy is one of the most powerful and open-source TCP/HTTP load balancers and reverse proxy solutions. In this guide, you will learn to install, configure, and optimize HAProxy as a High-Performance Reverse Proxy. If you are running your websites or applications on a VPS or dedicated server from PerLod Hosting, HAProxy is a great way to build a fast and stable reverse proxy in front of your services.
HAProxy operates at both Layer 4 (TCP) and Layer 7 (HTTP) of the OSI model, which offers unprecedented flexibility in traffic management.
TCP Mode: In this mode, HAProxy functions as a transparent TCP proxy, forwarding packets between clients and servers without inspecting packet contents.
HTTP Mode: When configured in HTTP mode, HAProxy gains full visibility into HTTP messages, enabling advanced features including URL-based routing, header manipulation, cookie insertion, content switching, SSL termination, and session persistence.
Now proceed to the following steps to complete the High-Performance Reverse Proxy Setup with HAProxy.
Requirements for High-Performance Reverse Proxy Setup with HAProxy
Before you start, make sure your server and network match these requirements:
A VPS or dedicated server with root or sudo access and supported OS such as Ubuntu 22.04/24.04 or a compatible RHEL-based distro.
Open inbound ports including 80/TCP (HTTP) and 443/TCP (HTTPS). Also, you can open 8404/TCP for the HAProxy stats page, which must be restricted by IP or authentication.
Allow outbound access from HAProxy to your backend servers, for example, 192.168.1.10:80, 192.168.1.20:8080, etc.
If you use HTTPs, you need DNS and SSL.
A domain pointing to your HAProxy public IP.
If you use certbot --standalone, port 80 must be reachable for HTTP-01 validation.
At least one backend web server or app that is reachable from HAProxy.
If you enable health checks like /health, make sure your app returns HTTP 200 on that endpoint.
Tip: If you need a high-performance VPS server, you can check PerLod, which offers flexible plans for your needs.
Install HAProxy as a High-Performance Reverse Proxy
HAProxy is available in the official Ubuntu repositories. For production deployments, you can use the PPA repository to access the latest version.
To install the latest HAProxy on Ubuntu 24.04 or 22.04, run the system update and install the software properties management tool with the commands below:
To verify the HAProxy service is active and running, use the command below:
Bash
sudosystemctlstatushaproxy
Basic HAProxy Reverse Proxy Configuration
The main HAProxy configuration file is located at /etc/haproxy/haproxy.cfg. In this step, we want to show you a minimal configuration for a reverse proxy setup with two backend web servers.
Before making changes, you must create a backup of the default configuration:
Then, edit the HAProxy main config file with the command below:
Bash
sudonano/etc/haproxy/haproxy.cfg
For a minimal reverse proxy configuration, you can edit the file as shown below:
Bash
#---------------------------------------------------------------------# Global settings#---------------------------------------------------------------------global# Run HAProxy as unprivileged user for securityuserhaproxygrouphaproxy# Run as background daemon processdaemon# Maximum concurrent connections (adjust based on system resources)maxconn4096# Logging configuration - send logs to local sysloglog/dev/loglocal0log/dev/loglocal1notice# Chroot to restricted directory for enhanced securitychroot/var/lib/haproxy# Create stats socket for runtime managementstatssocket/var/run/haproxy/admin.sockmode660leveladminstatstimeout 30s# SSL/TLS configuration for modern securityssl-default-bind-ciphersECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384ssl-default-bind-optionsssl-min-verTLSv1.2no-tls-tickets# Diffie-Hellman parameter size for SSLtune.ssl.default-dh-param2048#---------------------------------------------------------------------# Common defaults for all proxy sections#---------------------------------------------------------------------defaults# Operating mode - http enables Layer 7 featuresmodehttp# Inherit logging configuration from global sectionlogglobal# Enable detailed HTTP request loggingoptionhttplog# Do not log null connections (health checks, monitoring)optiondontlognull# Enable HTTP connection close on backend sideoptionhttp-server-close# Add X-Forwarded-For header with client IP addressoptionforwardforexcept127.0.0.0/8# Enable redistribution of requests on server failuresoptionredispatch# Number of connection retry attemptsretries3# Timeout settings for optimal performance and securitytimeoutconnect 10s# Time to establish backend connectiontimeoutclient 1m# Maximum client inactivity timetimeoutserver 1m# Maximum server response timetimeouthttp-request 10s# Maximum time to receive complete HTTP requesttimeouthttp-keep-alive 10s# HTTP keep-alive timeouttimeoutcheck 10s# Health check timeouttimeoutqueue 1m# Maximum time in queue when all servers busy#---------------------------------------------------------------------# Statistics dashboard (optional but recommended)#---------------------------------------------------------------------frontendstats# Listen on port 8404 for statistics pagebind*:8404# Enable statistics modulestatsenable# Set statistics URI pathstatsuri/stats# Auto-refresh intervalstatsrefresh 30s# Restrict admin access to localhostaclallowed_networksrc127.0.0.1192.168.1.0/24statsadminifallowed_network# Hide HAProxy version for securitystatshide-version# Set statistics page titlestatsrealmHAProxy\Statistics#---------------------------------------------------------------------# Frontend configuration - Client facing proxy#---------------------------------------------------------------------frontendhttp_front# Listen on all interfaces, port 80bind*:80# Set maximum connections for this frontendmaxconn2000# Default backend for unmatched requestsdefault_backendweb_servers#---------------------------------------------------------------------# Backend configuration - Pool of web servers#---------------------------------------------------------------------backendweb_servers# Load balancing algorithm# Options: roundrobin, leastconn, source, uri, etc.balanceroundrobin# Enable health checks on all serversoptionhttpchkGET/# Expect HTTP 200 response from health checkshttp-checkexpectstatus200# Server definitions# Format: server <name> <ip>:<port> [options]serverweb1192.168.1.10:80checkinter 3sfall3rise2serverweb2192.168.1.11:80checkinter 3sfall3rise2serverweb3192.168.1.12:80checkinter 3sfall3rise2
After the configuration setup, it is recommended to validate the syntax before restarting HAProxy. Validate configuration file syntax with the command below:
Bash
sudohaproxy-c-f/etc/haproxy/haproxy.cfg
You can use the command below to validate configs with warnings:
Bash
sudohaproxy-c-V-f/etc/haproxy/haproxy.cfg
In your output, you must see:
Bash
Configurationfileisvalid
If your HAProxy configuration is valid, you can restart it with the command below:
Bash
sudosystemctlrestarthaproxy
SSL and TLS Termination Configuration for HAProxy
SSL/TLS termination means HAProxy handles the HTTPS encryption and decryption itself, which makes the whole system faster and lets you manage SSL certificates in one central place.
For testing or Let's Encrypt integration, you can generate certificates using Certbot. Install Certbot with the commands below:
HAProxy requires certificates in PEM format with the certificate and private key concatenated into a single file. Create a directory for HAProxy certificates:
Bash
sudomkdir-p/etc/haproxy/certs
Combine the certificate and private key with the following command:
Now, open the HAProxy config file and add the following settings after the global and defaults sections. You can place the HTTPS and HTTP frontends before your backend web_servers block:
Bash
#---------------------------------------------------------------------# HTTPS Frontend with SSL Termination#---------------------------------------------------------------------frontendhttps_front# Listen on port 443 with SSL enabledbind*:443sslcrt/etc/haproxy/certs/example.com.pemalpnh2,http/1.1# Maximum connections for HTTPS frontendmaxconn2000# Add security headershttp-responseset-headerStrict-Transport-Security"max-age=31536000; includeSubDomains; preload"http-responseset-headerX-Frame-Options"SAMEORIGIN"http-responseset-headerX-Content-Type-Options"nosniff"http-responseset-headerX-XSS-Protection"1; mode=block"http-responseset-headerReferrer-Policy"strict-origin-when-cross-origin"# Set header to indicate HTTPS was usedhttp-requestset-headerX-Forwarded-Protohttps# Default backend for HTTPS requestsdefault_backendweb_servers#---------------------------------------------------------------------# HTTP Frontend - Redirect to HTTPS#---------------------------------------------------------------------frontendhttp_frontbind*:80# Redirect all HTTP traffic to HTTPShttp-requestredirectschemehttpscode301unless{ssl_fc}
For hosting multiple domains, HAProxy supports Server Name Indication (SNI) to select appropriate certificates. Create a certificate bundle directory with the command below:
2. Least Connections: Routes requests to the server with the fewest active connections. It is best for backends with varying request processing times or long-lived connections:
2. HTTP Health Checks: Advanced health checks using HTTP requests with expected response validation:
Bash
backendhttp_serversbalanceleastconn# Enable HTTP health checksoptionhttpchkGET/health# Expect HTTP 200 status codehttp-checkexpectstatus200# Servers with health check configurationserverweb1192.168.1.60:80checkinter 5sfall3rise2serverweb2192.168.1.61:80checkinter 5sfall3rise2
3. Advanced HTTP Health Checks: Multi-step health checks with custom headers and response validation:
Bash
backendadvanced_healthbalanceroundrobinoptionhttpchk# Send custom HTTP health check requesthttp-checksendmethGETuri/api/healthverHTTP/1.1hdrHostwww.example.com# Expect specific status codeshttp-checkexpectstatus200-299# Validate response contains specific stringhttp-checkexpectstring"healthy"serverapi1192.168.1.70:8080checkserverapi2192.168.1.71:8080check
HAProxy Logging Configuration
Logging is how you record what HAProxy is doing, so you can monitor traffic, troubleshoot problems faster, and review events for security checks.
In this step, you can configure your system’s logging service (rsyslog) to collect HAProxy logs into dedicated files, then enable logging inside HAProxy, and finally set up log rotation so the log files don’t fill up your disk.
Create rsyslog configuration for HAProxy with the command below:
Bash
sudonano/etc/rsyslog.d/49-haproxy.conf
Add the following configuration:
Bash
# Enable UDP syslog reception$ModLoadimudp$UDPServerRun514$UDPServerAddress127.0.0.1# HAProxy logging template$templateHaproxy,"%msg%\n"# Log all HAProxy messages to dedicated filelocal0.*-/var/log/haproxy/haproxy.log;Haproxy# Log only notice level and above to admin loglocal0.notice-/var/log/haproxy/haproxy-admin.log;Haproxy# Don't send HAProxy logs to other log files&stop
Create the HAProxy log directory and set appropriate permissions with the commands below:
HAProxy Smart Routing and Blocking Rules: Access Control Lists (ACLs)
ACLs rules in HAProxy let you detect things like the URL path, the domain name (Host header), the visitor’s IP, or the User-Agent, and then route the request to the right backend or block it if needed.
You can define an ACL, then use it with actions like use_backend (route) or http-request deny (block).
Basic ACL Syntax: ACLs consist of a name and a matching condition:
Bash
# ACL format: acl <name> <criterion> [flags] <value># Check if request path starts with /apiaclis_apipath_beg/api# Check if Host header matches domainaclis_domainhdr(host)-iexample.com# Check if client IP is in specific rangeaclinternal_networksrc192.168.1.0/24
Common ACL Use Cases include:
1. Path-Based Routing:
Bash
frontendhttp_frontbind*:80# Define ACLs for different pathsaclurl_staticpath_beg/static/images/css/jsaclurl_apipath_beg/apiaclurl_adminpath_beg/admin# Route to different backends based on pathuse_backendstatic_serversifurl_staticuse_backendapi_serversifurl_apiuse_backendadmin_serversifurl_admin# Default backend for unmatched requestsdefault_backendweb_servers
2. IP-Based Access Control:
Bash
frontendsecure_frontbind*:443sslcrt/etc/haproxy/certs/example.com.pem# Define allowed IP rangesaclallowed_ipssrc192.168.1.0/2410.0.0.0/8# Define admin pathsacladmin_pathpath_beg/admin# Block admin access from outside allowed IPshttp-requestdenyifadmin_path!allowed_ipsdefault_backendweb_servers
3. Host Header-Based Routing:
Bash
frontendhttp_frontbind*:80# Define ACLs for different domainsaclhost_app1hdr(host)-iapp1.example.comaclhost_app2hdr(host)-iapp2.example.comaclhost_apihdr(host)-iapi.example.com# Route to different backendsuse_backendapp1_serversifhost_app1use_backendapp2_serversifhost_app2use_backendapi_serversifhost_apidefault_backendweb_servers
4. User-Agent Filtering:
Bash
frontendhttp_frontbind*:80# Block requests from known bad botsaclbad_bothdr_sub(user-agent)-ibotcrawlerscraper# Deny bad bot requestshttp-requestdenyifbad_botdefault_backendweb_servers
HAProxy Session Persistence (Sticky Sessions)
Session persistence means that once a user is sent to a specific backend server, HAProxy will keep sending that same user back to the same server for future requests. This is important for apps that store user state on one server, because switching servers can log users out.
Cookie-based persistence: In this method, HAProxy adds a small cookie (like SERVERID) to the user’s browser so it can remember which backend server handled the first request.
Bash
backendweb_serversbalanceroundrobin# Insert session cookiecookieSERVERIDinsertindirectnocache# Servers with cookie identifiersserverweb1192.168.1.10:80checkcookieweb1serverweb2192.168.1.11:80checkcookieweb2serverweb3192.168.1.12:80checkcookieweb3
Cookie Options:
insert: HAProxy inserts the cookie.
indirect: Cookie not sent to backend servers.
nocache: Prevents caching of responses with cookies.
IP-based persistence (stick tables): In this method, HAProxy remembers the client by IP address and keeps routing that IP to the same backend server, without using cookies. Stick tables are basically an in-memory table that HAProxy uses to store this mapping.
expire 30m: Entries expire after 30 minutes of inactivity.
stick on src: Use client source IP as tracking key.
Rate Limiting and DDoS Protection in HAProxy
Rate limiting protects backend servers from abuse and DoS attacks. It’s a simple but very effective way to reduce abuse and slow down basic DoS/DDoS-style traffic floods.
Basic rate limiting (per IP): Here, HAProxy tracks each client IP and counts how many HTTP requests it makes in the last 10 seconds. If an IP goes above your limit, HAProxy blocks it with HTTP 429 Too Many Requests.
Advanced rate limiting (multiple counters): HAProxy tracks several signals at once. If a client looks abusive in any of these metrics, HAProxy flags it and blocks it.
Tarpit (slow down instead of block): A tarpit doesn’t instantly reject the attacker; it intentionally slows them down. This wastes the attacker’s resources and reduces pressure on your backends, while still letting real users through more easily.
HAProxy includes a built-in stats dashboard that shows live traffic and backend health, so you can quickly spot overload, failing servers, or unusual spikes. You can enable it by adding a small frontend stats block in your HAProxy config file.
Add statistics frontend to configuration:
Bash
frontendstatsbind*:8404modehttp# Enable statisticsstatsenable# Set statistics URIstatsuri/stats# Auto-refresh every 30 secondsstatsrefresh 30s# Restrict access to admin from specific IPsaclallowed_networksrc127.0.0.1192.168.1.0/24statsadminifallowed_network# Hide HAProxy version for securitystatshide-version# Set authentication (optional)statsauthadmin:SecurePassword123# Page titlestatsrealmHAProxy\Statistics
You can access the statistics page at:
HTML/XML
http://your-server-ip:8404/stats
The statistics dashboard displays essential metrics, including:
Session rate
Session total
Queue current
Queue max
Server status
Health check status
Active sessions
Bytes transferred
Response codes
Runtime API: The Runtime API lets you manage servers live using the admin socket without needing a full reload.
Bash
# Enable Runtime API socketglobalstatssocket/var/run/haproxy/admin.sockmode660leveladmin# Use socat to send commands# Show backend server statusecho"show servers state"|sudosocatstdio/var/run/haproxy/admin.sock# Disable server for maintenanceecho"disable server web_servers/web1"|sudosocatstdio/var/run/haproxy/admin.sock# Enable server after maintenanceecho"enable server web_servers/web1"|sudosocatstdio/var/run/haproxy/admin.sock# Set server to drain mode (finish existing connections, accept no new ones)echo"set server web_servers/web1 state drain"|sudosocatstdio/var/run/haproxy/admin.sock# View statisticsecho"show stat"|sudosocatstdio/var/run/haproxy/admin.sock
HAProxy Performance Tuning
Performance tuning means adjusting both the Linux system and HAProxy settings so they can handle lots of concurrent users without running out of resources or slowing down.
For system-level tuning, you can increase system limits for file descriptors:
Bash
sudonano/etc/security/limits.conf
Add the following lines to the file:
Bash
haproxysoftnofile65536haproxyhardnofile65536
Configure kernel parameters by editing the sysctl configuration:
Bash
sudonano/etc/sysctl.conf
Add performance parameters to the file:
Bash
# Increase maximum number of connection tracking entriesnet.netfilter.nf_conntrack_max=262144# Increase local port rangenet.ipv4.ip_local_port_range=102465535# Enable TCP fast opennet.ipv4.tcp_fastopen=3# Increase maximum backlognet.core.somaxconn=4096# Increase TCP max orphansnet.ipv4.tcp_max_orphans=65536# Increase max syn backlognet.ipv4.tcp_max_syn_backlog=20480# Enable TCP window scalingnet.ipv4.tcp_window_scaling=1# Reduce TIME_WAIT socketsnet.ipv4.tcp_fin_timeout=30
Apply changes with the command below:
Bash
sudosysctl-p
HAProxy tuning (inside haproxy.cfg): You can tune HAProxy limits so it can actually accept the load:
Bash
global# Maximum concurrent connections globally# Formula: (RAM_GB * 1024 * 1024 * 1024) / (16 * 1024) / 2maxconn20000# Number of threads (match CPU core count)nbthread4defaults# Maximum connections per frontendmaxconn10000backendweb_servers# Maximum connections per serverserverweb1192.168.1.10:80checkmaxconn500serverweb2192.168.1.11:80checkmaxconn500
Connection pooling (HTTP keep-alive): Enabling keep-alive allows HAProxy to reuse existing HTTP connections instead of opening a new connection for every request. This reduces TCP handshake overhead, lowers backend connection churn, and usually improves throughput and latency:
# Test SSL certificateopenssls_client-connectyour-server:443-servernameyour-domain.com# Check certificate expirationopensslx509-in/etc/haproxy/certs/example.com.pem-noout-dates# Verify certificate chainopensslverify-CAfile/etc/ssl/certs/ca-certificates.crt/etc/haproxy/certs/example.com.pem
Common causes:
Incomplete certificate chain.
Expired certificates.
Incorrect file permissions.
Missing intermediate certificates.
Conclusion
HAProxy is fast, flexible, and has many features, so it works well for everything from small projects to huge websites. If you use the setup examples and best practices in this guide, you can build a reverse proxy that is stable, secure, and able to handle very large traffic with very low delay.
We hope you enjoy this guide. Subscribe to our X and Facebook channels to get the latest updates and articles.
Use HTTP mode for websites and APIs because it supports routing by host, path, headers, redirects, and Layer 7 features. Use TCP mode for non-HTTP services.
Put it in /etc/haproxy/haproxy.cfg after global and defaults, and before backend sections.
Most of the time, it means HAProxy thinks all backends are DOWN, health check failing, or network access blocked.
We use cookies to run PerLod and to understand how the site is used. You can accept everything, or open Manage to turn individual categories off. Cookie policy.