Nginx默认的访问日志格式(通常在nginx.conf
中定义):
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
# 启用状态模块
location /nginx_status {
stub_status on;
access_log off;
allow 192.168.1.0/24;
deny all;
}
输出示例:
Active connections: 291
server accepts handled requests
16630948 16630948 31070465
Reading: 6 Writing: 179 Waiting: 106
requests per second = total requests / uptime
(active_connections / worker_connections) * 100
(error responses / total responses) * 100
location /admin/ {
allow 192.168.1.100;
allow 10.0.0.0/8;
deny all;
}
location /secure/ {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
创建密码文件:
htpasswd -c /etc/nginx/.htpasswd username
# 需要安装ngx_http_geoip_module
geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country {
default no;
US yes;
CA yes;
GB yes;
}
server {
if ($allowed_country = no) {
return 403;
}
}
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
location /api/ {
limit_req zone=one burst=20 nodelay;
proxy_pass http://backend;
}
}
location /dynamic-control {
access_by_lua_block {
local ip = ngx.var.remote_addr
local redis = require "resty.redis"
local red = redis:new()
red:connect("127.0.0.1", 6379)
local is_banned = red:get("banned:"..ip)
if is_banned == "1" then
ngx.exit(ngx.HTTP_FORBIDDEN)
end
}
}
# 限制单个IP的连接数
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
limit_conn addr 10;
# 限制特定URI的请求速率
location = /wp-login.php {
limit_req zone=one burst=3 nodelay;
}
}
# 阻止常见攻击
location / {
# 阻止SQL注入
if ($query_string ~* "union.*select.*\(") {
return 403;
}
# 阻止目录遍历
if ($uri ~* "\.\./") {
return 403;
}
# 限制HTTP方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
}
# 启用高效文件传输
sendfile on;
tcp_nopush on;
tcp_nodelay on;
# 保持连接设置
keepalive_timeout 65;
keepalive_requests 100;
# 缓冲区优化
client_body_buffer_size 10K;
client_header_buffer_size 1k;
client_max_body_size 8m;
large_client_header_buffers 4 16k;
location /metrics {
stub_status on;
access_log off;
# 自定义指标
content_by_lua_block {
metric_connections:set(ngx.var.connections_active, {"active"})
metric_requests:inc(1, {"total"})
}
}
# API速率限制
limit_req_zone $binary_remote_addr zone=api:10m rate=100r/s;
limit_req_zone $http_apikey zone=apikey:10m rate=50r/s;
server {
location /api/v1/ {
# 普通用户限制
limit_req zone=api burst=50;
# API密钥用户限制
if ($http_apikey) {
limit_req zone=apikey burst=20;
}
# 响应头中添加速率限制信息
add_header X-RateLimit-Limit $limit;
add_header X-RateLimit-Remaining $remaining;
proxy_pass http://api_backend;
}
}
http {
lua_shared_dict ip_blacklist 10m;
init_by_lua_block {
-- 初始化时从数据库加载黑名单
}
server {
access_by_lua_block {
local blacklist = ngx.shared.ip_blacklist
local ip = ngx.var.remote_addr
if blacklist:get(ip) then
ngx.exit(ngx.HTTP_FORBIDDEN)
end
}
location /report-abuse {
content_by_lua_block {
-- 处理滥用报告并更新黑名单
}
}
}
}
通过合理配置Nginx的流量分析和访问控制功能,可以显著提升Web应用的安全性、稳定性和性能。建议根据实际业务需求,选择适合的配置组合,并定期审查和优化安全策略。