要记录处理时间过长的请求,可以使用Nginx的ngx_http_log_module
和$request_time
变量。
http {
log_format slow_requests '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'rt=$request_time uct="$upstream_connect_time" uht="$upstream_header_time" urt="$upstream_response_time"';
server {
access_log /var/log/nginx/slow_requests.log slow_requests if=$slow_condition;
# 定义慢请求条件(例如响应时间超过2秒)
map $request_time $slow_condition {
default 0;
"~^[5-9]\." 1; # 5-9秒
"~^[1-9][0-9]" 1; # 10秒以上
}
}
}
server {
location / {
access_log /var/log/nginx/slow_requests.log slow_requests if=$slow_condition;
proxy_pass http://backend;
# 记录所有超过3秒的请求
set $threshold 3;
set $slow_condition 0;
if ($request_time > $threshold) {
set $slow_condition 1;
}
}
}
Nginx可以通过ngx_http_sub_module
模块实现响应内容替换。
检查Nginx是否包含--with-http_sub_module
编译选项。
server {
location / {
proxy_pass http://backend;
# 启用替换过滤器
sub_filter '原内容' '替换内容';
sub_filter_once off; # 替换所有匹配项而不仅是第一个
sub_filter_types text/html text/css application/javascript; # 指定MIME类型
# 当替换内容包含变量时需要设置
sub_filter_last_modified on;
}
}
location / {
proxy_pass http://backend;
# 多组替换
sub_filter '旧文本1' '新文本1';
sub_filter '旧文本2' '新文本2';
# 正则表达式替换(需要Nginx 1.9.4+)
sub_filter 'href="(.*?)"' 'href="https://newdomain.com$1"';
# 只对特定内容类型生效
sub_filter_types text/html;
# 确保代理头正确处理
proxy_set_header Accept-Encoding "";
}
http {
log_format slow_requests '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'rt=$request_time';
server {
listen 80;
server_name example.com;
access_log /var/log/nginx/access.log combined;
access_log /var/log/nginx/slow.log slow_requests if=$is_slow;
set $is_slow 0;
set $slow_threshold 2; # 2秒阈值
location / {
proxy_pass http://backend;
# 慢请求检测
if ($request_time > $slow_threshold) {
set $is_slow 1;
}
# 内容替换
sub_filter '旧公司名' '新公司名';
sub_filter '旧电话' '400-123-4567';
sub_filter_once off;
sub_filter_types text/html text/plain;
# 禁用上游gzip以允许内容替换
proxy_set_header Accept-Encoding "";
}
}
}
以上配置可以根据实际需求进行调整,如修改慢请求阈值、替换规则等。