Skip to content

HAProxy ACL 规则

ACL (Access Control List) 用于根据请求内容做流量控制和路由。

基本语法

acl <name> <criterion> [flags] [operator] <value> ...

常用条件

按路径匹配

# 匹配 /api 开头的请求
acl is_api path_beg /api

# 匹配 .php 结尾的请求
acl is_php path_end .php

按域名匹配

# 匹配 example.com
acl is_example hdr(host) -i example.com

# 匹配多个域名
acl is_static hdr(host) -i static.example.com img.example.com

按来源 IP

acl allowed_ip src 192.168.1.0/24
acl blocked_ip src 10.0.0.1

按 HTTP 方法

acl is_post method POST
acl is_get method GET

使用 ACL

拒绝访问

http-request deny if blocked_ip
http-request deny if !allowed_ip

路由到不同后端

acl is_api path_beg /api

use_backend api_servers if is_api
default_backend web_servers

重定向

acl is_mobile hdr(User-Agent) -i mobile

http-request redirect location /mobile if is_mobile

按文件类型限制

acl static_files path_end .css .js .jpg .png .gif .svg .woff2

http-request deny if !static_files method GET

常用标志

标志说明
-i忽略大小写
-f从文件加载规则
-m使用匹配方法

完整示例

frontend http_front
    bind *:80
    mode http

    # 定义 ACL
    acl is_api path_beg /api /v1
    acl is_static path_end .css .js .jpg .png .svg .woff2
    acl is_admin hdr_dom(host) -i admin.example.com

    # 静态资源
    use_backend static_servers if is_static

    # API 请求
    use_backend api_servers if is_api

    # 管理后台
    use_backend admin_servers if is_admin

    # 默认后端
    default_backend web_servers