nginx目錄結構和命令
1、ls /apps/nginx/: html是測試頁,sbin是主程序
2、ls /apps/nginx/sbin/: nginx 只有一個程序文件
3、ls /apps/nginx/html/: 50x.html index.html 測試網頁
nginx:默認爲啓動nginx
-h 查看幫助選項
-V 查看版本和配置選項
-t 測試nginx語法錯誤
-c filename 指定配置文件(default: /etc/nginx/nginx.conf)
-s signal 發送信號給master進程,signal:stop, quit, reopen, reload
示例: nginx -s stop 停止nginx
nginx -s reload 加載配置文件
-g directives 在命令行中指明全局指令
nginx配置
配置文件的組成部分:
主配置文件:nginx.conf
子配置文件 include conf.d/*.conf
fastcgi, uwsgi,scgi等協議相關的配置文件
mime.types:支持的mime類型
主配置文件的配置指令:
directive value [value2 ...];
注意:
(1) 指令必須以分號結尾
(2) 支持使用配置變量
內建變量:由Nginx模塊引入,可直接引用
自定義變量:由用戶使用set命令定義
set variable_name value;
引用變量:$variable_name
nginx配置文件
主配置文件結構:四部
main block:主配置段,即全局配置段,對http,mail都有效
event {
...
} 事件驅動相關的配置
http {
...
} http/https 協議相關配置段
mail {
...
} mail 協議相關配置段
stream {
...
} stream 服務器相關配置段
Main 全局配置段常見的配置指令分類
正常運行必備的配置
優化性能相關的配置
用於調試及定位問題相關的配置
事件驅動相關的配置
幫助文檔
http://nginx.org/en/docs/
http://tengine.taobao.org/nginx_docs/cn/docs/
nginx全局配置
正常運行必備的配置:
user nginx
指定worker進程的運行身份,如組不指定,默認和用戶名同名
Default: user nobody nobody;默認值是nobody,yum源安裝過程中會自動指定--user=ngxin,--group=nginx。
模塊加載配置文件: /usr/share/nginx/modules/*.conf
指明要裝載的動態模塊路徑: /usr/lib64/nginx/modules
性能優化相關的配置:
1、worker_processes 4(根據進程數修改數字) | auto; 啓動work工作進程數量,worker進程的數量;通常應該爲當前主機的cpu的物理核心數
2、worker_cpu_affinity 00000001 00000010 00000100 00001000; #將Nginx工作進程綁定到指定的CPU核心(當前代表的是8個CPU,4個work的意思),默認Nginx是不進行進程綁定的,綁定並不是意味着當前nginx進程獨佔用一核心CPU,但是可以保證此進程不會運行在其他核心上,這就極大減少了nginx的工作進程在不同的cpu核心上的來回跳轉,減少了CPU對進程的資源分配與回收以及內存管理等,因此可以有效的提升nginx服務器的性能。簡單來說就是提高緩存命中率。
CPU MASK:
00000001:0號CPU
00000010:1號CPU
10000000:7號CPU
3、worker_priority 0;指定worker進程的nice值,設定worker進程優先級:[-20,19],默認值是0。
4、worker_rlimit_nofile 65535; 這個數字包括Nginx的所有連接(例如與代理服務器的連接等),而不僅僅是與客戶端的連接,另一個考慮因素是實際的併發連接數不能超過系統級別的最大打開文件數的限制。
注意:所有worker進程能打開的文件數量上限,最好與ulimit -n 的值保持一致,如65535
示例:
查看當前有多少個CPU,和多少個work進程。
將nginx綁定在指定的CPU核心上,此配置在全局配置處修改。
查看此時CPU綁定效果,此時一個nginx進程綁定一個CPU。
[root@centos7~]#ps axo pid,cmd,psr |grep nginx
14190 vim nginx.conf 0
15015 nginx: master process nginx 3
15016 nginx: worker process 2
15017 nginx: worker process 0
15018 nginx: worker process 1
15019 nginx: worker process 0
15202 grep --color=auto nginx 3
事件驅動相關的配置:
events {
...
}
worker_connections #;
每個worker進程所能夠打開的最大併發連接數,如10240,總最大併發數:worker_processes * worker_connections,如果此時設置過大,服務器無法承受用戶訪問的併發量,會導致服務器癱瘓,用戶無法訪問,如果限制併發數,起到限流作用。
use method;指明併發連接請求的處理方法,默認自動選擇最優方法,默認就是epoll的IO模型,windows只支持select。
示例:use epoll;指定使用什麼類型的IO模型
處理新的連接請求的方法;on指由各個worker輪流處理新請求,Off指每個新請求的到達都會通知(喚醒)所有的worker進程,但只有一個進程可獲得連接,造成“驚羣”,影響性能,默認值爲off,可優化爲on。
accept_mutex on;
此指令默認爲off,即默認爲一個worker進程只能一次接受一個新的網絡連接, on表示每個woker進程可以同時接受所有新的網絡連接,默認值是off,可以優化爲on。
multi_accept on;
總結:對nginx參數可做優化的選項如下;
1、worker_processes number | auto;worker進程的數量;通常應該爲當前主機的cpu的物理核心數。
2、worker_cpu_affinity auto [cpumask] 0001 0010 0100 1000 (目前是4個CPU) 提高緩存命中率,有幾個物理CPU,將Nginx工作進程綁定到指定的CPU核心。
3、worker_connections #;每個worker進程所能夠打開的最大併發連接數,如10240,總最大併發數:worker_processes * worker_connections
4、accept_mutex on | off;處理新的連接請求的方法;on指由各個worker輪流處理新請求,Off指每個新請求的到達都會通知(喚醒)所有的worker進程,但只有一個進程可獲得連接,造成“驚羣”,影響性能,默認值爲off,可優化爲on。
5、multi_accept on|off; 此指令默認爲off,即默認爲一個worker進程只能一次接受一個新的網絡連接, on表示每個woker進程可以同時接受所有新的網絡連接
調試和定位問題:
1、daemon on|off; 是否以守護進程方式運行,默認是on,即守護進程方式,off 用於調試或docker環境,如果設置爲off,就是以前臺方式運行,方便調試。
2、master_process on|off;是否以master/worker模型運行nginx,默認爲on,當指定off 將不啓動worker
3、error_log file [level] ;錯誤日誌文件及其級別;出於調試需要,可設定爲debug;但debug僅在編譯時使用了“--with-debug”選項時纔有效
錯誤日誌默認在此路徑下:error_log /var/log/nginx/error.log;
http詳細配置
http協議的相關配置:
http {
... ...
server {
...
server_name
root
location [OPERATOR] /uri/ {
...
}
}
server {
...
}
}
在響應報文中將指定的文件擴展名映射至MIME對應的類型
include /etc/nginx/mime.types;
除上面指定的類型外,就爲默認的MIME類型,瀏覽器一般會提示下載
default_type application/octet-stream;
types {
text/html html;
image/gif gif;
image/jpeg jpg;
}
MIME參考文檔:
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_Types
在keepalived模式下的連接是否啓用TCP_NODELAY選項,即Nagle算法,當爲off時,延遲發送,每發送一個包就需要確認ACK,才發送下一個包。推薦使用on選項,不進行延遲發送。
默認On時,不延遲發送,多個包才確認一次。
可用於:http, server, location
tcp_nodelay on | off;
在開啓sendfile,on時合併響應頭和數據體在一個包中一起發送
tcp_nopush on | off ;
是否啓用sendfile功能,在內核中封裝報文直接發送,默認Off
sendfile on | off;
是否在響應報文中的Content-Type顯示指定的字符集,默認off不顯示
charset | off;
是否在響應報文的Server首部顯示nginx版本,默認是on,顯示版本的所有信息,不安全,推薦設置爲off,只顯示報文頭部信息。
server_tokens on | off | build | string;
自定義nginx版本信息
如果想自定義響應報文的nginx版本信息,需要修改源碼文件,重新編譯。
如果server_tokens on,修改 src/core/nginx.h 修改第13-14行,如下示例
#define NGINX_VERSION "1.68.9"
#define NGINX_VER "wanginx/" NGINX_VERSION
如果server_tokens off,修改 src/http/ngx_http_header_filter_module.c
第49行,如下示例:
static char ngx_http_server_string[] = "Server: nginx" CRLF;
把其中的nginx改爲自己想要的文字即可,如:wanginx
在源碼編譯中指定的版本中修改:vim /usr/local/src/nginx-1.16.1/src/core/nginx.h
ngx_http_core_module 所依賴的模塊
與套接字相關的配置:
server { ... }
配置一個虛擬主機
server {
listen address[:PORT]|PORT;
server_name SERVER_NAME;
root /PATH/TO/DOCUMENT_ROOT;
}
監聽端口和地址
listen PORT|address[:port]|unix:/PATH/TO/SOCKET_FILE 監聽端口
listen address[:port] [default_server] [ssl] [http2 | spdy] [backlog=number] [rcvbuf=size] [sndbuf=size]; 監聽地址
default_server 設定爲默認虛擬主機,無法匹配虛擬主機時使用
ssl 限制僅能夠通過ssl連接提供服務
backlog=number 超過併發連接數後,新請求進入後援隊列的長度
rcvbuf=size 接收緩衝區大小
sndbuf=size 發送緩衝區大小
注意:
(1) 基於port;
listen PORT; 指令監聽在不同的端口
(2) 基於ip的虛擬主機
listen IP:PORT; IP 地址不同
(3) 基於hostname
server_name fqdn; 指令指向不同的主機名
服務名稱多種寫法
server_name name ...;
虛擬主機的主機名稱後可跟多個由空白字符分隔的字符串
支持*通配任意長度的任意字符
server_name *.magedu.com www.magedu.*
支持~起始的字符做正則表達式模式匹配,性能原因慎用
server_name ~^www\d+\.magedu\.com$
說明: \d 表示 [0-9]
匹配優先級機制從高到低
(1) 首先是字符串精確匹配 如:www.magedu.com
(2) 左側*通配符 如:*.magedu.com
(3) 右側*通配符 如:www.magedu.*
(4) 正則表達式 如: ~^.*\.magedu\.com$
(5) default_server
定義路徑相關的配置
root
設置web資源的路徑映射;用於指明請求的URL所對應的文檔的目錄路徑,可用於http, server, location, if in location
server {
...
root /data/www/vhost1;
}
示例
http://www.magedu.com/images/logo.jpg 訪問頁面
--> /data/www/vhosts/images/logo.jpg 實際訪問的是此路徑的文件
location詳細用法
location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
在一個server中location配置段可存在多個,用於實現從uri到文件系統的路徑映射;ngnix會根據用戶請求的URI來檢查定義的所有location,並找出一個最佳匹配,而後應用其配置。
root:指定web的家目錄,在定義location的時候,文件的絕對路徑等於 root+location,如:
server {
listen 80;
server_name www.magedu.net;
location / {
root /data/nginx/html/pc;
}
location /about {
root /data/nginx/html/pc; #必須要在pc目錄中創建一個about目錄纔可以訪問,否則報錯。
index index.html;
}
}
[root@s2 ~]# mkdir /data/nginx/html/pc/about
[root@s2 ~]# echo about > /data/nginx/html/pc/about/index.html
在沒有使用正則表達式的時候,nginx會先在server中的多個location選取匹配度最高的一個uri,uri是用戶請求的字符串,即域名後面的web文件路徑,然後使用該location模塊中的正則url和字符串,如果匹配成功就結束搜索,並使用此location處理此請求。
語法規則: location [=|~|~*|^~] /uri/ { … }
= #用於標準uri前,需要請求字串與uri精確匹配,如果匹配成功就停止向下匹配並立即處理請求。
~ #表示包含正則表達式並且區分大小寫
~* #表示包含正則表達式並且不區分大寫
!~ #表示包含正則表達式並且區分大小寫不匹配
!~* #表示包含正則表達式並且不區分大小寫不匹配
^~ #表示包含正則表達式並且匹配以什麼開頭
$ #表示包含正則表達式並且匹配以什麼結尾
\ #表示包含正則表達式並且轉義字符。可以轉. * ?等
* #表示包含正則表達式並且代表任意長度的任意字符
匹配優先級從高到低:
=, ^~, ~/~*, 不帶符號
示例:各location對應的優先級:
location = / { A:http://www.magedu.com/ 此行對應A選項
[ configuration A ]
}
location / { B:http://www.magedu.com/index.html 此行對應B選項
[ configuration B ]
}
location /documents/ { E:http://www.magedu.com/documents/logo.jpg 此行對應E選項
[ configuration C ]
}
location ^~ /images/ { C:http://www.magedu.com/documents/linux.txt 此行對應C選項
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ { D: http://www.magedu.com/images/logo.jpeg 此行對應D選項
[ configuration E ]
}
實現動靜分離:
在配置文件中修改:vim /etc/nginx/conf.d/test.conf
server {
server_name www.baidu.net;
root /data/site1/;
location ~* \.(jpg|gif|html|txt|js|css)$ {
root /opt/static;
}
location ~ \.(php|jsp|asp) {
root /opt/dynamic;
}
}
root與alias詳細用法:
路徑別名,文檔映射的另一種機制;僅能用於location上下文
http://www.magedu.com/bbs/index.html
location /bbs { 注意: /bbs 後建議不要加 /
alias /web/forum;
} --> /web/forum/index.html 實際訪問的此文件路徑
location /bbs/ {
root /web/forum/;
} --> /web/forum/bbs/index.html
注意:location中使用root指令和alias指令的意義不同
(a) root,給定的路徑對應於location中的/uri 左側的/
(b) alias,給定的路徑對應於location中的/uri 的完整路徑
alias定義路徑別名,會把訪問的路徑重新定義到其指定的路徑,如下示例:
server {
listen 80;
server_name www.magedu.net;
location / {
root /data/nginx/html/pc;
}
#使用alias的時候uri後面如果加了斜槓則下面的路徑配置必須加斜槓,否則403
location /about {
#當訪問about時,訪問alias定義的/opt/nginx/html/pc內容
alias /opt/nginx/html/pc;
index index.html;
}
}
A主機:192.168.37.27
B主機:192.168.37.17
1、在nginx服務器的目錄下設置alias別名路徑。
[root@centos27~]#vim /etc/nginx/conf.d/test.conf 在此目錄下進行創建nginx別名
server {
server_name www.baidu.net;
location ~ \.(php|jsp|asp) {
root /opt/dynamic;
}
location /about {
alias /opt/testdir; 定義路徑別名,對應about目錄後面最都不要加/
}
}
啓動nginx服務:nginx或者systemctl start nginx
2、在nginx服務器上新建index.html文件
[root@centos27~]#mkdir /opt/testdir/about -pv 新建一個about目錄
[root@centos27~]#echo /opt/testdir/about/index.html > /opt/testdir/about/index.html 在about目錄下新建一個index.html文件
[root@centos27~]#echo /opt/testdir/index.html > /opt/testdir/index.html 在testdir目錄下新建一個index.html文件
3、在客戶端的hosts配置文件中加上域名解析。
[root@centos17~]#vim /etc/hosts
192.168.37.27 www.baidu.net
4、訪問nginx服務器about目錄下默認的index.html文件,此時實際訪問的是別名目錄下的index.html文件。
[root@centos17~]#curl www.baidu.net/about/ 實際訪問的是about目錄下的文件
/opt/testdir/index.html 實際訪問的是testdir目錄下的文件
指定默認主頁(建議不要設置默認文件)
1、在nginx服務器上創建一個虛擬服務,並啓動nginx服務。
[root@centos27~]#vim /etc/nginx/conf.d/test.conf
server {
server_name www.baidu.net;
location /about {
root /opt/testdir/; 指定目錄,尋找默認文件會在about目錄下尋找。
index test.html;
}
}
2、在nginx服務器上創建默認的test.html文件。
[root@centos27~]#echo /opt/testdir/about/test.html > /opt/testdir/about/test.html
3、在客戶端訪問about目錄,此時就會訪問創建的默認test.html文件。
[root@centos17~]#curl www.baidu.net/about/
/opt/testdir/about/test.html
自定義錯誤頁面
1、在nginx服務器新建一個錯誤虛擬主機
[root@centos27site1]#vim /etc/nginx/conf.d/test.conf
server {
server_name www.baidu.net;
root /data/site1;
error_page 500 502 503 404 /error.html;
location = /error.html {
}
}
2、nginx的/data/site1目錄下新建對應的錯誤文件。
[root@centos27site1]#cd /data/site1
[root@centos27site1]#echo baidu 500.html > error.html
[root@centos27site1]#echo baidu 502.html >> error.html
[root@centos27site1]#echo baidu 503.html >> error.html
[root@centos27site1]#echo baidu 504.html >> error.html
3、在客戶端訪問錯誤的html文件,就會顯示對應的錯誤信息。
[root@centos17~]#curl www.baidu.net/xxx.html
baidu 500.html
baidu 502.html
baidu 503.html
baidu 504.html
我們可以將錯誤的404信息進行重定向爲200 OK的響應,此時訪問的網頁就不會被攔截,只會提示報錯。
生產中案例:
listen 80;
server_name www.magedu.net;
error_page 500 502 503 504 404 /error.html;
location = /error.html {
root /data/nginx/html;
}
監測文件是否存在
try_files file ... uri;
try_files file ... =code;
按順序檢查文件是否存在,返回第一個找到的文件或文件夾(結尾加斜線表示爲文件夾),如果所有文件或文件夾都找不到,會進行一個內部重定向到最後一個參數。只有最後一個參數可以引起一個內部重定向,之前的參數只設置內部URI的指向。最後一個參數是回退URI且必須存在,否則會出現內部500錯誤。
location /images/ {
try_files $uri /images/default.jpg;
} 說明:/images/default.jpg 爲 URI
location / {
try_files $uri $uri/index.html $uri.html =404;
}
1、在nginx服務端創建一個判斷文件爲空的虛擬機
vim /etc/nginx/conf.d/test.conf
server {
server_name www.baidu.net;
location /images {
alias /data/images;
try_files $uri /images/default.jpg; 在指定的uri尋找文件,此時如果找不到就會默認尋找默認文件
#try_files $uri $uri/default.jpg;
}
}
2、在nginx服務器端新建幾個文件,作爲測試,如果訪問的頁面不存在,就會返回指定的默認文件。
[root@centos27site1]#mkdir /data/images
[root@centos27site1]#echo www.a.jgp> /data/images/default.jpg
[root@centos27site1]#echo www.default.jgp> /data/images/default.jpg
[root@centos27site1]#echo www.a.jpg > /data/images/a.jpg
[root@centos27site1]#echo www.b.jpg > /data/images/b.jpg
3、在客戶端進行測試效果。
[root@centos17~]#curl www.baidu.net/images/xxx.jpg 當輸入不存在的文件時,就會返回默認的文件
www.default.jgp
[root@centos17~]#curl www.baidu.net/images/b.jpg
www.b.jpg
[root@centos17~]#curl www.baidu.net/images/a.jpg
www.a.jpg
[root@centos17~]#curl www.baidu.net/images/xxx.jpg
www.default.jgp
也可以自定義狀態:
vim /etc/nginx/conf.d/test.conf
server {
server_name www.baidu.net;
location /images {
alias /data/images;
#try_files $uri /images/default.jpg; 此處的uri對應的是/images/default.jpg路徑
try_files $uri $uri/default.jpg =598; 自定義錯誤狀態598,
}
}
刪除nginx服務端默認的default.jpg文件。
[root@centos27images]#rm -rf default.jpg
在客戶端進行訪問,此時由於沒有默認的default.jpg文件,就會返回自定義的錯誤狀態碼。
[root@centos17~]#curl -I www.baidu.net/images/xxx.jpg
HTTP/1.1 598 錯誤狀態碼 598
Server: nginx/1.16.1
Date: Thu, 12 Dec 2019 04:31:37 GMT
Content-Length: 0
Connection: keep-alive
Keep-Alive: timeout=65
長久連接配置
設定保持連接超時時長,0表示禁止長連接,默認爲75s
keepalive_timeout timeout [header_timeout];
示例:在響應頭顯示此首部字段
keepalive_timeout 60 60;
在一次長連接上所允許請求的資源的最大數量,默認爲100
keepalive_requests number;
對哪種瀏覽器禁用長連接
keepalive_disable none | browser ...;
向客戶端發送響應報文的超時時長,此處是指兩次寫操作之間的間隔時長,而非整個響應過程的傳輸時長
send_timeout time;
作爲上傳服務器
指定請求報文中實體的最大值,設爲0,則不限制,默認1M,超過報413錯誤
client_max_body_size size;
用於接收每個客戶端請求報文的body部分的緩衝區大小;默認爲16k;超出此大小時,其將被暫存到磁盤上的由下面client_body_temp_path指令所定義的位置
client_body_buffer_size size;
設定存儲客戶端請求報文的body部分的臨時存儲路徑及子目錄結構和數量
client_body_temp_path path [level1 [level2 [level3]]];
目錄名爲16進制的數字;用hash之後的值從後往前截取第1、2、3級作爲文件名
client_body_emp_path /var/tmp/client_body 1 2 2
1 1級目錄佔1位16進制,即2^4=16個目錄 0-f
2 2級目錄佔2位16進制,即2^8=256個目錄 00-ff
2 3級目錄佔2位16進制,即2^8=256個目錄 00-ff
生產案例
配置示例:
client_max_body_size 10m;
client_body_buffer_size 16k;
client_body_temp_path /apps/nginx/temp 1 2 2; #reload Nginx會自動創建temp目錄
作爲下載服務器配置
對客戶端進行限制的相關配置
limit_rate rate;
限制響應給客戶端的傳輸速率,單位是bytes/second,默認值0表示無限制。
實戰演示:
1、在nginx服務器上設置限速問題下載文件,並重啓Nginx服務。
vim /etc/nginx/conf.d/test.conf
server {
server_name www.baidu.net;
root /data/site1;
limit_rate 10k; 限速下載爲10kB每秒
location /about {
root /opt/testdir/;
index test.html;
}
location /images {
alias /data/images;
#try_files $uri /images/default.jpg;
try_files $uri $uri/default.jpg =598;
}
}
2、在nginx服務端/data/site1目錄下新建一個1G大文件。
[root@centos27~]#dd if=/dev/zero of=/data/f1 bs=1M count=1024
1024+0 records in
1024+0 records out
1073741824 bytes (1.1 GB) copied, 26.4264 s, 40.6 MB/s
3、在客戶端進行下載此文件, 此時可以看到文件的下載速度。
limit_except method ... { ... },僅用於location
限制客戶端使用除了指定的請求方法之外的其它方法
method:GET, HEAD, POST, PUT, DELETE,MKCOL, COPY, MOVE, OPTIONS, PROPFIND, PROPPATCH, LOCK, UNLOCK, PATCH
limit_except GET {
allow 192.168.1.0/24;
deny all;
}
除了GET和HEAD 之外其它方法僅允許192.168.1.0/24網段主機使用
示例:
NGINX服務器上配置指令信息。
客戶端訪問結果:
[root@centos17~]#curl -XOPTIONS -I www.baidu.net
HTTP/1.1 405 Not Allowed nginx資源不支持此方式(OPTIONS)
Server: nginx/1.16.1
Date: Thu, 12 Dec 2019 07:10:16 GMT
Content-Type: text/html
Content-Length: 157
Connection: keep-alive
Keep-Alive: timeout=65
文件操作優化的配置
是否啓用aio功能,默認off
aio on | off | threads[=pool];
當文件大於等於給定大小時,同步(直接)寫磁盤,而非寫緩存,默認off
directio size | off;
示例:
location /video/ {
sendfile on;
aio on;
directio 8m;
}
緩存配置
open_file_cache off;
open_file_cache max=N [inactive=time];
1、nginx可以緩存以下三種信息:
(1) 文件元數據:文件的描述符、文件大小和最近一次的修改時間
(2) 打開的目錄結構
(3) 沒有找到的或者沒有權限訪問的文件的相關信息
2、max=N:可緩存的緩存項上限;達到上限後會使用LRU算法實現管理
3、inactive=time:緩存項的非活動時長,在此處指定的時長內未被命中的或命中的次數少於open_file_cache_min_uses指令所指定的次數的緩存項即爲非活動項,將被刪除
4、是否緩存查找時發生錯誤的文件一類的信息,默認值爲off
open_file_cache_errors on | off;
5、open_file_cache指令的inactive參數指定的時長內,至少被命中此處指定的次數方可被歸類爲活動項,默認值爲1
open_file_cache_min_uses number;
6、緩存項有效性的檢查頻率,默認值爲60s
open_file_cache_valid time;
示例:
open_file_cache max=10000 inactive=6 0s;
open_file_cache_valid 30s;
open_file_cache_min_uses 5;
open_file_cache_errors on;
模塊配置:
一、ngx_http_access_module模塊:可實現基於ip的訪問控制功能。
allow address | CIDR | unix: | all;
deny address | CIDR | unix: | all;
http, server, location, limit_except
自上而下檢查,一旦匹配,將生效,條件嚴格的置前
示例:
location = /login/ {
root /data/nginx/html/pc;
}
location /about {
alias /data/nginx/html/pc;
index index.html;
deny 192.168.1.1;
allow 192.168.1.0/24;
allow 10.1.1.0/16;
allow 2001:0db8::/32;
deny all; #先允許小部分,再拒絕大部分
}
二、ngx_http_auth_basic_module模塊:實現基於用戶的訪問控制,使用basic機制進行用戶認證
auth_basic string | off;
auth_basic_user_file file;
location /admin/ {
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.ngxpasswd;
}
用戶口令文件:
1、明文文本:格式name:password:comment
2、加密文本:由htpasswd命令實現
httpd-tools所提供
演示:
1、在nginx服務端安裝httpd-tools包
[root@centos27~]#yum install httpd-tools -y
2、nginx服務端,創建文件的用戶名和密碼
[root@centos27~]#htpasswd -b -c /etc/nginx/conf.d/.nginx_passwd alice centos 創建alice用戶
Adding password for user alice
[root@centos27~]#htpasswd -b /etc/nginx/conf.d/.nginx_passwd bob centos 創建bob用戶
Adding password for user bob
3、nginx服務端,創建指定的Index.html文件
[root@centos27~]#mkdir /data/admin
[root@centos27~]#echo /data/admin/index.html > /data/admin/index.html
4、修改虛擬主機的配置文件
vim /etc/nginx/conf.d/test.conf
server {
server_name www.Mrliu.net;
root /data/site1;
limit_rate 10k;
location /about {
root /opt/testdir/;
index test.html;
}
location /admin { 指定目錄文件
root /data/ ;
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/conf.d/.passwd_nginx; 修改指定的加密文件路徑
}
}
三、ngx_http_stub_status_module模塊
用於輸出nginx的基本狀態信息, 輸出信息示例:
Active connections: 291
server accepts handled requests #下面三個數分別對應accepts,handled,requests
16630948 16630948 31070465
Reading: 6 Writing: 179 Waiting: 106
Active connections:當前狀態,活動狀態的連接數
accepts:統計總值,已經接受的客戶端請求的總數
handled:統計總值,已處理完成的客戶端請求總數,一般和accepts相同,除非拒絕
requests:統計總值,客戶端發來的總的請求數
Reading:當前狀態,正在讀取客戶端請求報文首部的連接的連接數
Writing:當前狀態,正在向客戶端發送響應報文過程中的連接數
Waiting:當前狀態,正在等待客戶端發出請求的空閒連接數
實戰演示:
1、在nginx服務端進行設置
vim /etc/nginx/conf.d/test.conf
server_name www.baidu.net;
root /data/site1;
limit_rate 10k;
location /about {
root /opt/testdir/;
index test.html;
}
location /admin {
root /data/ ;
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/conf.d/.passwd_nginx;
}
location /nginx_status {
stub_status;
allow 127.0.0.1;
allow 172.16.0.0/16;
allow 192.168.37.0/24;
deny all;
}
}
2、客戶端訪問效果:
[root@centos17~]#curl www.baidu.net/nginx_status
Active connections: 1
server accepts handled requests
1 1 1
Reading: 0 Writing: 1 Waiting: 0
nginx 第三方模塊
第三模塊是對nginx 的功能擴展,第三方模塊需要在編譯安裝nginx 的時候使用參數--add-module=PATH指定路徑添加,有的模塊是由公司的開發人員針對業務需求定製開發的,有的模塊是開源愛好者開發好之後上傳到github進行開源的模塊,nginx支持第三方模塊,需要重新編譯源碼才能支持。
開源的echo模塊,實現輸出變量等信息
https://github.com/openresty/echo-nginx-module
示例:編譯安裝nginx時,最好下載1.14.2版本,16版本暫時不兼容。
#yum install git –y
#cd /usr/local/src
#git clone https://github.com/openresty/echo-nginx-module.git
#cd nginx-1.14.0/
#useradd –r –s /sbin/nologin nginx
#yum install gcc pcre-devel openssl-devel zlib-devel perl-ExtUtils-Embed
1、安裝git包
[[email protected]]#yum install git
2、切換到/usr/loca/src目錄下,並對網站進行克隆
[root@centos17src]#cd /usr/local/src
[root@centos17src]#git clone https://github.com/openresty/echo-nginx-module.git 克隆網站鏈接
Cloning into 'echo-nginx-module'...
remote: Enumerating objects: 15, done.
remote: Counting objects: 100% (15/15), done.
remote: Compressing objects: 100% (12/12), done.
remote: Total 3012 (delta 6), reused 7 (delta 3), pack-reused 2997
Receiving objects: 100% (3012/3012), 1.15 MiB | 171.00 KiB/s, done.
Resolving deltas: 100% (1617/1617), done.
[root@centos17src]#ls echo-nginx-module/
config LICENSE README.markdown src t util valgrind.suppress
3、安裝依賴的包,並創建系統賬號
cd nginx-1.14.0/
useradd –r –s /sbin/nologin nginx
yum install gcc pcre-devel openssl-devel zlib-devel perl-ExtUtils-Embed
4、在解壓後的nginx目錄下進行編譯。
./configure \
--prefix=/apps/nginx \
--user=nginx --group=nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-http_perl_module \
--with-pcre \
--with-stream \
--with-stream_ssl_module \
--with-stream_realip_module \
--add-module=/usr/local/src/echo-nginx-module
5、最後安裝指定的目錄文件
[[email protected]]#make -j 4 && make install
示例:
vim /apps/nginx/conf/conf.d/pc.conf
location /test {
index index.html;
default_type text/html;
echo "hello world,main-->";
echo_reset_timer;
echo_location /sub1;
echo_location /sub2;
echo "took $echo_timer_elapsed sec for total.";
}
location /sub1 {
echo_sleep 1;
echo sub1;
}
location /sub2 {
echo_sleep 1;
echo sub2;
}
測試結果:
nginx 變量使用
nginx的變量可以在配置文件中引用,作爲功能判斷或者日誌等場景使用,變量可以分爲內置變量和自定義變量,內置變量是由nginx模塊自帶,通過變量可以獲取到衆多的與客戶端訪問相關的值
常見內置變量
1、$remote_addr;#存放了客戶端的地址,注意是客戶端的公網IP
2、$args;#變量中存放了URL中的指令
http://www.magedu.net/main/index.do?id=090&partner=search
以上:id=090&partner=search 即爲 $args
3、$document_root;#保存了針對當前資源的請求的系統根目錄,如/apps/nginx/html
4、$cookie_name; #表示key爲 name 的cookie值
5、$document_uri;#保存了當前請求中不包含指令的URI,注意是不包含請求的指令,如http://www.magedu.net/main/index.do?id=090&partner=search會被定義爲/main/index.do
6、$host;#存放了請求的host名稱
7、$http_user_agent;#客戶端瀏覽器的詳細信息
8、$http_cookie;#客戶端的cookie信息
9、$limit_rate;#如果nginx服務器使用limit_rate配置了顯示網絡速率,則會顯示,如果沒有設置, 則顯示0
10、$remote_port;#客戶端請求Nginx服務器時客戶端隨機打開的端口
11、$remote_user;#已經經過Auth Basic Module驗證的用戶名
12、$request_body_file;#做反向代理時發給後端服務器的本地資源的名稱
13、$request_method;#請求資源的方式,GET/PUT/DELETE等
14、$request_filename;#當前請求的資源文件的路徑名稱,由root或alias指令與URI請求生成的文件絕對路徑,如/apps/nginx/html/main/index.html
15、$request_uri;#包含請求參數的原始URI,不包含主機名
如:main/index.do?id=090&partner=search。
16、$scheme;#請求的協議,如ftp,https,http等
17、$server_protocol;#請求資源的協議版本,如HTTP/.0,HTTP/.,HTTP/.0等
18、$server_addr;#保存了服務器的IP地址
19、$server_name;#請求的服務器的主機名
20、$server_port;#請求的服務器的端口
實戰演練:
1、在nginx服務端新建一個echo模塊配合變量的文件,並啓動nginx服務。
2、在nginx服務端新建一個echo目錄,並在echo目錄下新建一個test.html文件。
[root@centos17conf]#echo /apps/nginx/conf/echo/test.html > /apps/nginx/conf/echo/index.html
[root@centos17conf]#nginx -s reload
3、在客戶端訪問nginx的IP地址,可以看到echo回顯的結果,並在屏幕上打印index.html文件結果。
[root@centos27~]#curl 192.168.37.17/echo
hello word
192.168.37.27
挑選了幾個自定義變量,就不在一一列舉:
自定義變量:
自定義變量名稱和值,使用指令 set $variable value
格式如下:
set $variable value;
支持:server, location, if
示例:
set $name magedu;
echo $name;
set $my_port $server_port;
echo $my_port;
echo "$server_name:$server_port";
1、ngx_http_log_module模塊:指定日誌格式記錄請求
2、log_format name string ...;string可以使用nginx核心模塊及其它模塊內嵌的變量
3、access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
4、access_log off; #禁用訪問日誌
5、訪問日誌文件路徑,格式及相關的緩衝的配置
buffer=size
flush=time
自定義json日誌格式
nginx 的默認訪問日誌記錄內容相對比較單一,默認的格式也不方便後期做日誌統計分析,生產環境中通常將nginx日誌轉換爲json日誌,然後配合使用ELK做日誌收集-統計-分析。
1、在rpm包安裝的nginx配置文件中定義json日誌格式。
log_format access_json '{"@timestamp":"$time_iso8601",'
'"host":"$server_addr",'
'"clientip":"$remote_addr",'
'"size":$body_bytes_sent,'
'"responsetime":$request_time,'
'"upstreamtime":"$upstream_response_time",'
'"upstreamhost":"$upstream_addr",'
'"http_host":"$host",'
'"uri":"$uri",'
'"domain":"$host",'
'"xff":"$http_x_forwarded_for",'
'"referer":"$http_referer",'
'"tcp_xff":"$proxy_protocol_addr",'
'"http_user_agent":"$http_user_agent",'
'"status":"$status"}';
2、在nginx服務器的/etc/nginx/conf.d/test.conf配置文件中指定json日誌文件路徑。
源碼編譯安裝後的路徑:access_log /apps/nginx/logs/access_json.log access_json;
server {
access_log /var/log/nginx/access_json.log access_json;
server_name www.baidu.net;
root /data/site1;
}
3、跟蹤日誌文件tail -f /var/log/nginx/access_json.log
4、當日志文件過大時,我們可以將有用的log日誌文件進行備份,然後再進行清理日誌,不要刪除日誌文件,刪除的話就要重啓nginx,而清空日誌,不需要重啓,還會繼續跟蹤日誌文件。
[root@centos27site1]#> /var/log/nginx/access_json.log 可以直接重定向清空文件,有些shell類型不支持,那就用下面的方法也可以清空日誌
[root@centos27site1]#cat /dev/null > /var/log/nginx/access_json.log 清空日誌
json格式的日誌訪問統計,python代碼統計
cat nginx_json.py
#!/usr/bin/env python
#coding:utf-8
status_200= []
status_404= []
with open("access_json.log") as f:
for line in f.readlines():
line = eval(line)
if line.get("status") == "200":
status_200.append(line.get)
elif line.get("status") == "404":
status_404.append(line.get)
else:
print("狀態碼 ERROR")
f.close()
print "狀態碼200的有--:",len(status_200)
print "狀態碼404的有--:",len(status_404)
ngx_http_autoindex_module
配置文件下載服務
1、autoindex on | off;自動文件索引功能,默爲off
2、autoindex_exact_size on | off; 計算文件確切大小(單位bytes),off 顯示大概大小(單位K、M),默認on
3、autoindex_localtime on | off ;顯示本機時間而非GMT(格林威治)時間,默認off=
4、autoindex_format html | xml | json | jsonp;顯示索引的頁面文件風格,默認html
實戰演練:
配置文件下載服務生產案例
vim /etc/nginx/conf.d/test.conf
location /download {
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
autoindex_format json;
limit_rate 100k;
index index.html;
}
2、在nginx服務端的光盤掛載downlaod目錄,將光盤的文件掛載到download目錄下,方便下載文件。
[root@centos27site1]#mount /dev/sr0 /data/site1/download/
3、此時在客戶端上就可以訪問www.baidu.net/download,就會訪問放光盤掛載的文件信息。
關於favicon.ico
favicon.ico 文件是瀏覽器收藏網址時顯示的圖標,當使用瀏覽器訪問頁面時,瀏覽器會自己主動發起請求獲取頁面的favicon.ico文件,但是當瀏覽器請求的favicon.ico文件不存在時,服務器會記錄404日誌,而且瀏覽器也會顯示404報錯
解決方案:
服務器不記錄訪問日誌:
location = /favicon.ico {
log_not_found off; #文件沒發現事件不記錄error_log
access_log off; #不記錄access_log
}
將圖標保存到指定目錄訪問:
#location ~ ^/favicon\.ico$ {
location = /favicon.ico {
root /data/nginx/html/pc/images;
}