Traefik不提供封禁IP的功能,但是可以结合其他工具实现IP封禁。
一种建议的实现方式是使用fail2ban(一个工具,可以根据特定的规则来检测和封禁恶意的IP地址)。以下是所需步骤:
1.在Traefik的配置文件中设置后端地址(可以是本地服务器上的任何应用程序,如Nginx,Apache等):
[backends]
[backends.mybackend]
[backends.mybackend.servers.server1]
url = "http://localhost:8080"
weight = 5
- 为Traefik的Frontend配置添加回调URL。
[frontends]
[frontends.myfrontend]
backend = "mybackend"
passHostHeader = true
[frontends.myfrontend.routes.test_1]
rule = "HostRegexp:{subdomain:.*}.domain.com"
priority = 10
[frontends.myfrontend.routes.test_2]
rule = "PathPrefixStrip:/app/"
priority = 20
[frontends.myfrontend.routes.test_3]
rule = "PathPrefix:/dashboard/"
priority = 30
[frontends.myfrontend.headers.customResponseHeaders]
# Add custom headers here
X-Content-Type-Options = "nosniff"
X-Frame-Options = "SAMEORIGIN"
X-XSS-Protection = "1; mode=block"
[frontends.myfrontend.headers.customRequestHeaders]
# Add custom request headers here
Authorization = "Bearer {JWT_TOKEN}"
[frontends.myfrontend.callbacks]
[frontends.myfrontend.callbacks.fail2ban]
sendTCPClientIP = true
url = "http://127.0.0.1:8080/fail2ban"
- 启动Fail2ban,并为Traefik核心关键字创建规则。
例如:
[traefik]
enabled = true
filter = traefik
action = iptables-allports[name=traefik, protocol=all]
logpath = /var/log/messages
maxretry = 3
bantime = 3600
- 最后,为Traefik添加一个路由规则,以将请求转发到您的封禁脚本,以便自动添加到fail2ban的过滤列表中:
[entryPoints.http.redirect]
entryPoint = "https"
# HTTPS configuration here
[entryPoints.http]
address = ":80"
forwardedHeaders = ["X-Forwarded-Proto"]
[entryPoints.http.redirect]
entryPoint = "https"
[entryPoints.traefik]
address = ":8080"
[http.middlewares]
[http.middlewares.ipwhitelist.ipWhiteList]
sourceRange = ["192.168.0.0/16", "172.16.0.0/12", "10.0.0.0/8"]
[http.middlewares.banip.addPrefix]
prefix = "/fail2ban"
[http.middlewares.banip.ipBan]
# Add IP addresses to ban here
bannedIPs = ["192.168.100.100"]
[http.routers]
[http.routers.banip]
rule = "PathPrefix(`/fail2ban`)"
middlewares = ["banip"]
service = "dummy@internal"
[http.routers.myrouter]
rule = "Host(`example.com`) && Path(`/`)"
middlewares = ["ipwhitelist"]
service = "myservice@internal"
tls = true
这里是让外层进行封禁的方式。