Nginx出现未初始化logging变量报错,是否需为error_log添加if=$logging?
First, let's break down why you're seeing that error message. The problem stems from the scope of your $logging variable. Right now, you're likely initializing $logging inside a location block, which means it only exists within that specific context. When a malicious crawler sends a request that triggers an error before Nginx processes that location (like an invalid URL that doesn't match any location, or an early-stage request error), the $logging variable hasn't been set yet—hence the "uninitialized variable" warning.
Step 1: Fix the Uninitialized Variable Error
To resolve this, you need to initialize the $logging variable at the server block level (outside any location blocks). This ensures the variable exists in all request contexts, even when errors occur early in the pipeline.
Here's how to adjust your config:
server { # Initialize $logging at the server level to avoid uninitialized errors set $logging 1; # Check if the request is from an excluded bot if ($bot_in_log = 0) { set $logging 0; } # Check if the request is from an excluded IP if ($ip_in_log = 0) { set $logging 0; } # Conditional access log (your existing setup) access_log /var/log/nginx/access.log combined if=$logging; # ... rest of your server configuration ... }
Step 2: Should You Add if=$logging to error_log?
This depends on your goal:
- If you want to exclude error logs from the same bots/IPs that you're blocking from access logs, then yes—adding the
if=$loggingcondition toerror_logwill achieve that. Update your error_log line to:error_log /var/log/nginx/error.log warn if=$logging; - If you don't mind logging errors from those excluded bots/IPs (e.g., you want to track malicious activity even if you're ignoring their access logs), you can leave
error_logas-is—just make sure you've completed Step 1 to fix the uninitialized variable error.
A quick note: Nginx supports the if parameter for error_log starting from version 1.7.0, so ensure your Nginx installation is up-to-date if you decide to use this.
内容的提问来源于stack exchange,提问作者JoaMika

