
我在 Ubuntu 14.04 伺服器上使用預設的 nginx 套件。它用作/etc/nginx/nginx.conf
主要配置,然後包含來自/etc/nginx/conf.d/*.conf
和 的配置/etc/nginx/sites-enabled/*
。
預設的 nginx 設定有這個指令用來記錄到存取日誌
access_log /var/log/nginx/access.log;
我想添加 X-Forwarded-For 標頭,因此我在conf.d
資料夾內執行此操作:
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
我遇到的問題是,然後我在 access.log 檔案中得到兩條記錄 - 一條包含標題訊息,另一則沒有標題訊息。
我知道我可以覆蓋nginx.conf
文件本身,但如果可能的話我寧願避免它。我還想繼續使用相同的日誌檔案 ( access.log
)。
有沒有辦法告訴nginx覆蓋前面的指令並簡單地更改日誌格式而不修改主nginx.conf
文件?
答案1
你的問題的答案是否定的,你不能在nginx中的任何級別覆蓋log_format,並且在同一級別時你不能覆蓋access_log,除非將其關閉。不過,您可以在不更改 nginx.conf 的情況下實現您想要的效果,但您必須在伺服器 {} 層級執行此操作。
這裡的問題是 conf.d/* 的 include 位於 http {} 內,這正是 access_log 指令所在的位置。您可以在不接觸 nginx.conf 的情況下更改您正在使用的伺服器(如果您沒有設定伺服器,那麼您將使用位於 /etc/nginx/sites-enabled/default 的預設伺服器)。因此,要在不更改 nginx.conf 的情況下實現相同的目標,您應該將 conf.d 資料夾中的檔案更改為:
log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log off;
然後在您的伺服器{}中輸入:
access_log /var/log/nginx/access.log main;
這應該能讓你得到你一開始想要的東西。