一、配置優先級簡述
在 Nginx 中,
http
、server
、location
?模塊下配置相同策略時是存在優先級的,一般遵循 “范圍越小,優先級越高” 的原則,下面為你詳細介紹:1. 配置繼承關系
http
?塊:作為全局配置塊,其中的配置會對所有的?server
?塊生效,屬于最寬泛的配置范圍。server
?塊:定義虛擬主機,其配置會覆蓋?http
?塊中相同的配置,適用于特定的域名或 IP 地址。location
?塊:處于?server
?塊內部,用于匹配特定的 URI 路徑,其配置會覆蓋?server
?塊和?http
?塊中相同的配置,是最精細的配置范圍。
二、實驗驗證
以日志配置為例
實驗準備:
步驟一:在http模塊定義日志
配置在http塊下配置日志
http {...#配置日志log_format myformat '訪問URL: $request_uri';access_log logs/http.log myformat;...
}
步驟二:在server和location塊下定義日志
server {...access_log logs/server.log myformat;...location /location {...access_log logs/location.log myformat;...}
}
步驟三:定義兩個server 三個訪問url?
server配置
server {listen 443 ssl;ssl_certificate /usr/local/nginx/conf/ssl/gateway.crt;ssl_certificate_key /usr/local/nginx/conf/ssl/gateway.key;server_name 192.168.72.130;root /opt/xxx;location /http {#這里設置內部重定向,將http開頭的請求重定向到根目錄下rewrite ^/http(.*)$ /$1 break;# 開啟目錄列表展示功能autoindex on;# 以可讀格式顯示文件大小autoindex_exact_size off;# 以本地時間顯示文件修改時間autoindex_localtime on;}
}server {listen 80;server_name 192.168.72.130; # 替換為你的域名gzip on;#配置日志access_log logs/server.log myformat;# 網站根目錄,即要暴露內容的目錄root /opt/xxx;location /server {#這里設置內部重定向,將server開頭的請求重定向到根目錄下rewrite ^/server(.*)$ /$1 break;# 開啟目錄列表展示功能autoindex on;# 以可讀格式顯示文件大小autoindex_exact_size off;# 以本地時間顯示文件修改時間autoindex_localtime on;}location /location {#這里設置內部重定向,將 /location 開頭的請求重定向到根目錄下rewrite ^/location(.*)$ /$1 break;#配置日志access_log logs/location.log myformat;# 開啟目錄列表展示功能autoindex on;# 以可讀格式顯示文件大小autoindex_exact_size off;# 以本地時間顯示文件修改時間autoindex_localtime on;}
}
三、實驗結果?
因為在location中有定義日志所以日志輸出直接采用location中的策略
?因為在location中沒有定義日志所以日志輸出采用server中的策略
?因為在location和server中都沒有定義日志,所以日志輸出采用server中的策略
結論:
在 Nginx 中,http
、server
、location
?模塊下配置相同策略時是存在優先級的,一般遵循 “范圍越小,優先級越高” 的原則,