3.2 nginxHTTP塊配置
1 配置塊的嵌套
http {
upstream {...}
split_clients {...}
map {...}
geo {...}
server {
if () {...}
location {
limit_except {...}
}
location {
location {
}
}
}
server {
}
}
2 指令的合并
- 值指令:存儲配置項的值
- 可以合并
- 示例:root,access_log,gzip
- 動作類指令:指定行為
- 不可以合并
- 示例:rewrite,proxy_pass
- 生效階段:server_rewrite階段,rewrite階段,content階段
存儲值的指令繼承規則:向上覆蓋
- 子配置不存在時,直接使用父配置塊
- 子配置存在時,直接覆蓋父配置塊
server {
listen 8080;
root /home/geek/nginx/html;
access_log logs/geek.access.log main;
location /test {
root /home/geek/nginx/test;
access_log logs/access.test.log main;
}
location /dlib {
alias dlib/;
}
location / {
}
}
3 HTTP請求處理時的11個階段


4 正則表達式


5 提取用戶真實ip
如何拿到真實的用戶ip地址?

拿到真實用戶ip后如何使用?
基于變量:如binary_remote_addr、remote_addr這樣的變量,其值就為真實的IP!這樣做連接限制(limit_conn模塊)才有意義!
步驟
-
安裝realip模塊
realip是Nginx內置模塊,需要在編譯Nginx時加上
--with-http_realip_module參數來啟用它。 -
配置語法
set_real_ip_from 192.168.1.0/24; #真實服務器上一級代理的IP地址或者IP段,可以寫多行。 set_real_ip_from 192.168.2.1; real_ip_header X-Forwarded-For; #從哪個header頭檢索出要的IP地址。 real_ip_recursive on; #遞歸的去除所配置中的可信IP。這里詳細講下
real_ip_recursive的用途:遞歸的去除所配置中的可信IP,排除set_real_ip_from里面出現的IP。如果出現了未出現這些IP段的IP,那么這個IP將被認為是用戶的IP。 -
配置實例
location / { root html/; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; set_real_ip_from 192.168.1.0/24; set_real_ip_from 192.168.2.1; real_ip_header X-Forwarded-For; real_ip_recursive on; }
6 定義404錯誤頁面
6.1 Nginx自己的錯誤頁面
Nginx訪問一個靜態的html 頁面,當這個頁面沒有的時候,Nginx拋出404,那么如何返回給客戶端404呢?
看下面的配置,這種情況下不需要修改任何參數,就能實現這個功能。
server {
listen 80;
server_name www.test.com;
root /var/www/test;
index index.html index.htm;
location / {
}
# 定義錯誤頁面碼,如果出現相應的錯誤頁面碼,轉發到那里。
error_page 404 403 500 502 503 504 /404.html;
# 承接上面的location
location = /404.html {
# 放錯誤頁面的目錄路徑。
root /usr/share/nginx/html;
}
}
6.2 反向代理的錯誤頁面
如果后臺Tomcat處理報錯拋出404,想把這個狀態叫Nginx反饋給客戶端或者重定向到某個連接,配置如下:
upstream www {
server 192.168.1.201:8080 weight=20 max_fails=2 fail_timeout=30s
ip_hash;
}
server {
listen 80;
server_name www.test.com;
root /var/www/test;
index index.html;
location / {
if($request_uri ~* '^/$') {
rewrite .* http://www.test2.com/index.html redirect;
}
# 關鍵參數:這個變量開啟后,我們才能自定義錯誤頁面,當后端返回404,nginx攔截錯誤,定義錯誤頁面
proxy_intercept_errors on;
proxy_pass http://www;
proxy_set_header HOST $host;
}
error_page 404 /404.html;
location = /404.html {
root /usr/share/nginx/html;
}
}
6.3 Nginx解析php代碼的錯誤頁面
如果后端是php解析的,需要加一個變量
在http段中加一個變量
fastcgi_intercept_errors on就可以了。
時間是個偉大的作者,必將給出完美的答案。

浙公網安備 33010602011771號