A lightweight Lua-based Nginx traffic control system that limits total network traffic (default 1 TB). Once the limit is reached, further requests are blocked with a 403 error.
- Accurately tracks total request traffic.
- Automatically persists traffic data every 60 seconds.
- Automatically loads traffic data after Nginx reload/restart.
- Provides a
/getTrafficStatus
API endpoint returning real-time usage data. - Supports customizable traffic limit thresholds.
- Sends an alert (via a shell script) when traffic exceeds the threshold.
/etc/nginx/lua/traffic_control.lua
/etc/nginx/lua/traffic_alert.sh
/etc/nginx/logs/traffic_counter.txt
/etc/nginx/lua_traffic_limit.conf
- Install OpenResty or Nginx with Lua module.
- Place
traffic_control.lua
under/etc/nginx/lib/lua/
. you can set own config. - Add Lua configurations to your
nginx.conf
as shown in the sample config. - Prepare the alert script
/etc/nginx/lua/traffic_alert.sh
. - Restart Nginx.
- visit your site: https://your.domain/getTrafficStatus. Don't forget to add auth_basic.
- Endpoint:
/getTrafficStatus
- Response Example:
{
"timestamp": 1714380297,
"total_out_traffic": "512.36 GB",
"limit_traffic": "1024.00 GB",
"used_percent": "50.03%",
"current_month": "2025-05"
}
#!/bin/bash
echo "Traffic limit exceeded!" | mail -s "Traffic Alert" your_email@example.com
Make sure the script has executable permissions:
chmod +x /etc/nginx/lua/traffic_alert.sh
Lua modules must be enabled in Nginx.
The default traffic limit is set to 1TB. You can adjust it inside traffic_control.lua.
You can extend the alert mechanism to Telegram, Slack, SMS, etc.