正常運(yùn)行必備的配置參數(shù)
user USERNAME [GROUPNAME]; //指定運(yùn)行worker進(jìn)程的用戶和組 ,指定以哪個組和哪個用戶的身份去運(yùn)行软族,組可寫可不寫
pid /path/to/pid_file; //指定nginx守護(hù)進(jìn)程的pid文件
worker_rlimit_nofile number; //設(shè)置所有worker進(jìn)程最大可以打開的文件數(shù)咒唆,默認(rèn)為1024
worker_rlimit_core size; //指明所有worker進(jìn)程所能夠使用的總體的最大核心文件大小,保持默認(rèn)即可
user USERNAME [GROUPNAME]
因?yàn)檫@個地方注釋了,所以依然是nginx用戶去執(zhí)行
[root@localhost conf]# head -2 nginx.conf
#user nobody;
[root@localhost conf]# ps -ef | grep nginx
root 1088 1 0 14:14 ? 00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx 1089 1088 0 14:14 ? 00:00:00 nginx: worker process
nginx 1090 1088 0 14:14 ? 00:00:00 nginx: worker process
nginx 1091 1088 0 14:14 ? 00:00:00 nginx: worker process
root 45167 1363 0 17:40 pts/0 00:00:00 grep --color=auto nginx
最好改為nginx
[root@localhost conf]# head -2 nginx.conf
user nginx nginx;
pid /path/to/pid_file; //指定nginx守護(hù)進(jìn)程的pid文件
nginx的守護(hù)進(jìn)程的文件存放的位置
守護(hù)進(jìn)程的pid文件存放在安裝目錄下的logs下的
nginx.pid //默認(rèn)存放的位置
[root@localhost conf]# vim nginx.conf
[root@localhost conf]# pwd
/usr/local/nginx/conf
9 #pid logs/nginx.pid; //雖然注釋了但依然有效茫藏,當(dāng)你使用這個某個文件時(shí)最好將注釋取消,告訴系統(tǒng)文件位置
[root@localhost logs]# pwd
/usr/local/nginx/logs
[root@localhost logs]# ls
error.log nginx.pid
worker_rlimit_nofile number; //設(shè)置所有worker進(jìn)程最大可以打開的文件數(shù),默認(rèn)為1024
就是worker進(jìn)程最多能打開1024個文件數(shù)沮趣,最好將值調(diào)整至65535最大的值。這個值是因?yàn)槎丝谔栕疃嘀挥?5535
這個在nginx的配置文件默認(rèn)沒有坷随,這需要我們自己手動添加
[root@localhost conf]# head -4 nginx.conf
user nginx nginx;
worker_processes 3;
worker_rlimit_nofile 65535;
檢查nginx語法看是否有問題
[root@localhost conf]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost conf]# systemctl restart nginx.service //重啟服務(wù)
因?yàn)槲覀儎偛攀窃O(shè)置的是nginx的訪問數(shù)量房铭,但是系統(tǒng)默認(rèn)還是1024,需要將系統(tǒng)的1024也改為65535温眉,猜可以生效缸匪,因?yàn)橄到y(tǒng)是包含nginx這個服務(wù)的
沒修改之前的
[root@localhost security]# ulimit -a
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 23060
max locked memory (kbytes, -l) 64
max memory size (kbytes, -m) unlimited
open files (-n) 1024
所以我們此時(shí)需要設(shè)置系統(tǒng)的支持的訪問數(shù)量
[root@localhost security]# pwd
/etc/security
[root@localhost security]# tail -3 limits.conf //在文件的最后一行添加下面兩行內(nèi)容
# End of file
* soft nofile 65535
* hard nofile 65535
此時(shí)在使用ulimit -a命令去查看
[root@localhost ~]# systemctl restart nginx.service
[root@localhost ~]# ulimit -a | grep -w 65535
open files (-n) 65535
worker_rlimit_core size; //指明所有worker進(jìn)程所能夠使用的總體的最大核心文件大小,保持默認(rèn)即可這個東西很少使用
優(yōu)化性能的配置參數(shù)
這個是用來優(yōu)化nginx的worker運(yùn)行的效率
worker_processes n; //啟動n個worker進(jìn)程类溢,這里的n為了避免上下文切換凌蔬,通常設(shè)置為cpu總核心數(shù)-1或等于總核心數(shù)
worker_cpu_affinity cpumask ...; //將進(jìn)程綁定到某cpu中,避免頻繁刷新緩存
//cpumask:使用8位二進(jìn)制表示cpu核心闯冷,如:
0000 0001 //第一顆cpu核心
0000 0010 //第二顆cpu核心
0000 0100 //第三顆cpu核心
0000 1000 //第四顆cpu核心
0001 0000 //第五顆cpu核心
0010 0000 //第六顆cpu核心
0100 0000 //第七顆cpu核心
1000 0000 //第八顆cpu核心
timer_resolution interval; //計(jì)時(shí)器解析度砂心。降低此值,可減少gettimeofday()系統(tǒng)調(diào)用的次數(shù)
worker_priority number; //指明worker進(jìn)程的nice值
worker_processes n; //啟動n個worker進(jìn)程蛇耀,這里的n為了避免上下文切換辩诞,通常設(shè)置為cpu總核心數(shù)-1或等于總核心數(shù)
什么是上下文切換?
上下文切換就是從當(dāng)前執(zhí)行任務(wù)切換到另一個任務(wù)執(zhí)行的過程纺涤。但是躁倒,為了確保下次能從正確的位置繼續(xù)執(zhí)行,在切換之前洒琢,會保存上一個任務(wù)的狀態(tài)秧秉。下一次會接著上一個任務(wù)運(yùn)行退出的地方接著運(yùn)行。
為了避免上下文切換若你是8核的cpu給7核到nginx進(jìn)程使用衰抑,剩余的給其他系統(tǒng)服務(wù)使用象迎。
worker_cpu_affinity cpumask ...; //將進(jìn)程綁定到某cpu中,避免頻繁刷新緩存
將進(jìn)程綁定到某個cpu核心中
[root@localhost conf]# head -5 nginx.conf
user nginx nginx;
worker_processes 1;
worker_cpu_affinity 0001 0010
然后使用top命令,再點(diǎn)擊L鍵呛踊,輸入nginx就可以找到nginx的進(jìn)程
top - 19:14:24 up 6 min, 4 users, load average: 0.15, 0.17, 0.11
Tasks: 135 total, 1 running, 134 sleeping, 0 stopped, 0 zombie
%Cpu(s): 0.8 us, 3.1 sy, 0.0 ni, 96.0 id, 0.0 wa, 0.0 hi, 0.1 si, 0.0 st
KiB Mem : 5927960 total, 5605320 free, 143528 used, 179112 buff/cache
KiB Swap: 6160380 total, 6160380 free, 0 used. 5544388 avail Mem
PR PID USER NI %CPU VIRT RES SHR S %MEM TIME+ COMMAND P
20 1653 root 0 0.0 115932 2392 1644 S 0.0 0:00.01 bash 1
20 5173 root 0 0.0 77364 1356 240 S 0.0 0:00.00 nginx 2
20 5174 nginx 0 0.0 77740 2168 636 S 0.0 0:00.00 nginx 0
20 12626 root 0 0.0 0 0 0 S 0.0 0:00.00 kworker/0:
再按f鍵就會跳到這個頁面砾淌,按上下左右的下鍵將光標(biāo)移至P那一行,點(diǎn)擊空格鍵選中谭网,按q退出就可以看到汪厨,nginx進(jìn)程使用的cpu了,并綁定成功愉择,也不會進(jìn)行上下文切換了
* PR = Priority PPID = Parent Pr nTH = Number of SUPGIDS = Supp Grou nsUTS = UTS names
* PID = Process I UID = Effective * P = Last Used SUPGRPS = Supp Grou
* USER = Effective RUID = Real User TIME = CPU Time TGID = Thread Gr
* NI = Nice Valu RUSER = Real User SWAP = Swapped S ENVIRON = Environme
* %CPU = CPU Usage SUID = Saved Use CODE = Code Size vMj = Major Fa
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND P
1604 root 20 0 116032 2656 1780 S 0.0 0.0 0:00.05 bash 2
1653 root 20 0 115932 2392 1644 S 0.0 0.0 0:00.01 bash 1
1771 root 20 0 162796 3068 1592 S 0.0 0.1 0:01.49 top 0
5173 root 20 0 77364 1356 240 S 0.0 0.0 0:00.00 nginx 2
5174 nginx 20 0 77740 2168 636 S 0.0 0.0 0:00.00 nginx 0
worker_priority number; //指明worker進(jìn)程的nice值
優(yōu)先級分為兩種一個實(shí)時(shí)優(yōu)先級劫乱,一個相對優(yōu)先級
能控制的優(yōu)先級有40個數(shù)织中,-20到19 對應(yīng)100-139
nice是數(shù)字越低優(yōu)先級越高。
[root@localhost conf]# head -5 nginx.conf
user nginx nginx;
worker_processes 1;
worker_cpu_affinity 0001 0010;
worker_priority -20;
[root@localhost conf]# systemctl restart nginx.service
使用top命令
11243 nginx 0 -20 77740 2188 640 S 0.0 0.0 0:00.00 nginx
[root@localhost opt]# ps -elf | grep nginx
1 S root 11242 1 0 80 0 - 19341 sigsus 20:05 ? 00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
5 S nginx 11243 11242 0 60 -20 - 19435 ep_pol 20:05 ? 00:00:00 nginx: worker process
0 S root 16510 2288 0 80 0 - 28206 pipe_w 20:08 pts/2 00:00:00 grep --c
事件相關(guān)的配置:event{}段中的配置參數(shù)
這些東西保持默認(rèn)即可
accept_mutex {off|on}; //master調(diào)度用戶請求至各worker進(jìn)程時(shí)使用的負(fù)載均衡鎖衷戈;on表示能讓多個worker輪流地狭吼、序列化地去響應(yīng)新請求
lock_file file; //accept_mutex用到的互斥鎖鎖文件路徑
use [epoll | rtsig | select | poll]; //指明使用的事件模型,建議讓nginx自行選擇
worker_connections #; //每個進(jìn)程能夠接受的最大連接數(shù)
accept_mutex //是互斥鎖
worker_connection //最好我們自行設(shè)置
worker_connections #; //每個進(jìn)程能夠接受的最大連接數(shù)
這是作為壓測的工具
[root@localhost conf]# vim nginx.conf
14 events {
15 worker_connections 20480;
[root@localhost conf]# systemctl restart nginx.service
若沒有ab命令就請安裝httpd-tools包組
[root@localhost conf]# yum -y install httpd-tools
-c 用于指定的并發(fā)數(shù)殖妇;-n 用于指定壓力測試總共的執(zhí)行次數(shù)
[root@localhost conf]# ab -c 100 -n 5000 http://192.168.182.131/index1.html
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking 192.168.182.131 (be patient)
Completed 500 requests
Completed 1000 requests
Completed 1500 requests
Completed 2000 requests
Completed 2500 requests
Completed 3000 requests
Completed 3500 requests
Completed 4000 requests
Completed 4500 requests
Completed 5000 requests
Finished 5000 requests
Server Software: nginx/1.20.1
Server Hostname: 192.168.182.131
Server Port: 80
Document Path: /index1.html
Document Length: 153 bytes
Concurrency Level: 100
Time taken for tests: 0.390 seconds
Complete requests: 5000
Failed requests: 0
Write errors: 0
Non-2xx responses: 5000
Total transferred: 1515000 bytes
HTML transferred: 765000 bytes
Requests per second: 12825.64 [#/sec] (mean)
Time per request: 7.797 [ms] (mean)
Time per request: 0.078 [ms] (mean, across all concurrent requests)
Transfer rate: 3795.09 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 3 2.4 3 35
Processing: 1 5 5.3 3 49
Waiting: 0 4 4.9 3 47
Total: 3 8 6.0 6 52
Percentage of the requests served within a certain time (ms)
50% 6
66% 7
75% 8
80% 8
90% 11
95% 15
98% 20
99% 49
100% 52 (longest request)
網(wǎng)絡(luò)連接相關(guān)的配置參數(shù)
keepalive_timeout number; //長連接的超時(shí)時(shí)長刁笙,默認(rèn)為65s
keepalive_requests number; //在一個長連接上所能夠允許請求的最大資源數(shù)
keepalive_disable [msie6|safari|none]; //為指定類型的UserAgent禁用長連接
tcp_nodelay on|off; //是否對長連接使用TCP_NODELAY選項(xiàng),為了提升用戶體驗(yàn)谦趣,通常設(shè)為on
client_header_timeout number; //讀取http請求報(bào)文首部的超時(shí)時(shí)長
client_body_timeout number; //讀取http請求報(bào)文body部分的超時(shí)時(shí)長
send_timeout number; //發(fā)送響應(yīng)報(bào)文的超時(shí)時(shí)長
keepalive_timeout number //65s內(nèi)沒做任何操作就超時(shí)退出
keepalive_requests number //連接建立之后可以設(shè)置一個值疲吸,這個值就是要處理的請求,當(dāng)請求全部處理完成之后才退出
keepalive_disable [msie6|safari|none] //disabl可以在http前鹅,server磅氨,location中配置,在什么地方配置就對哪個地方生效(也就是禁用某個瀏覽器的長連接)嫡纠,這里的msie6|safari是瀏覽器的類型,none就是空任何類型都可以訪問
[root@localhost conf]# vim nginx.conf
34 keepalive_disable msie6;
tcp_nodelay on|off //設(shè)置使用長連接沒有延遲延赌,默認(rèn)也是no
fastcgi的相關(guān)配置參數(shù)
LNMP:php要啟用fpm模型
配置示例如下:
location ~ \.php$ {
root html;
fastcgi_pass 127.0.0.1:9000; //定義反向代理
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
include fastcgi_params;
}
常需要進(jìn)行調(diào)整的參數(shù)
- worker_processes
- worker_connections
- worker_cpu_affinity
- worker_priority
nginx作為web服務(wù)器時(shí)使用的配置:http{}段的配置參數(shù)
http{...}:配置http相關(guān)除盏,由ngx_http_core_module模塊引入。nginx的HTTP配置主要包括四個區(qū)塊挫以,結(jié)構(gòu)如下:
若想要配置HTTP可以到官網(wǎng)相關(guān)的模塊進(jìn)行參考
https://nginx.org/en/docs/http/ngx_http_core_module.html
http {//協(xié)議級別
include mime.types;
default_type application/octet-stream;
keepalive_timeout 65;
gzip on;
upstream {//負(fù)載均衡配置
...
}
server {//服務(wù)器級別者蠕,每個server類似于httpd中的一個<VirtualHost> //這個就類似于一個網(wǎng)站
listen 80;
server_name localhost;
location / {//請求級別,類似于httpd中的<Location>掐松,用于定義URL與本地文件系統(tǒng)的映射關(guān)系
root html;
index index.html index.htm;
}
}
}
部署一個http的頁面
[root@localhost test]# cat index.html
test web
[root@localhost test]# pwd
/usr/local/nginx/html/test
[root@localhost conf]# vim nginx.conf
[root@localhost conf]# pwd
/usr/local/nginx/conf
36 #gzip on;
37
38 server {
39 listen 82;
40 server_name test.example.com;
41
42 location / {
43 root html/test;
44 index index.html;
45 }
46 }
檢查nginx的語法
[root@localhost conf]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: [warn] the number of "worker_processes" is not equal to the number of "worker_cpu_affinity" masks, using last mask for remaining worker processes
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
重啟nginx服務(wù)
[root@localhost conf]# systemctl restart nginx.service
[root@localhost conf]# ss -anlt
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:80 *:*
LISTEN 0 128 *:82 *:*
LISTEN 0 128 *:22 *:*
http{}段配置指令:
server {}:定義一個虛擬主機(jī)踱侣,示例如下:
server {
listen 80;
server_name www.idfsoft.com;
root "/vhosts/web";
}
listen:指定監(jiān)聽的地址和端口
listen address[:port];
listen port;
server_name NAME [...]; 后面可跟多個主機(jī),名稱可使用正則表達(dá)式或通配符
當(dāng)有多個server時(shí)大磺,匹配順序如下:
1. 先做精確匹配檢查
2. 左側(cè)通配符匹配檢查抡句,如*.idfsoft.com
3. 右側(cè)通配符匹配檢查,如mail.*
4. 正則表達(dá)式匹配檢查杠愧,如~ ^.*\.idfsoft\.com$
5. default_server
root path;設(shè)置資源路徑映射待榔,用于指明請求的URL所對應(yīng)的資源所在的文件系統(tǒng)上的起始路徑
alias path;用于location配置段,定義路徑別名
index file; 默認(rèn)主頁面
index index.php index.html;
為了安全可以通過root path流济;設(shè)置資源路徑映射
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
alias /var/www/html/; //alias的特點(diǎn)是的必須跟上絕對路徑
index index.html index.htm;
}
[root@localhost ~]# mkdir -p /var/www/html/ //將test目錄放在此目錄下
[root@localhost html]# mv /usr/local/nginx/html/test ./
[root@localhost html]# ls
test
[root@localhost ~]# systemctl restart nginx.service
error_page code [...] [=code] URI | @name 根據(jù)http響應(yīng)狀態(tài)碼來指明特用的錯誤頁面锐锣,例如 error_page 404 /404_customed.html //404表示服務(wù)端無法找到客戶端想要請求的資源,響應(yīng)狀態(tài)碼為“NOT Found”绳瘟,當(dāng)出現(xiàn)此類型的報(bào)錯就會使用404_customed.html 這個文件里面的內(nèi)容進(jìn)行響應(yīng)
[=code]:以指定的響應(yīng)碼進(jìn)行響應(yīng)雕憔,而不是默認(rèn)的原來的響應(yīng),默認(rèn)表示以新資源的響應(yīng)碼為其響應(yīng)碼糖声,例如 error_page 404 =200 /404_customed.html
log_format 定義日志格式:
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 logs/access.log main;
//注意:此處可用變量為nginx各模塊內(nèi)建變量
404頁面的配置
隨便到百度里面找一個網(wǎng)頁來替代404頁面斤彼,以此來檢測效果
[root@localhost conf]# vim nginx.conf
48 error_page 404 /404.html; //取消注釋
[root@localhost html]# pwd
/usr/local/nginx/html
[root@localhost html]# mv 程序員客棧-領(lǐng)先的程序員自由遠(yuǎn)程工作平臺.html 404.html
[root@localhost html]# ls
404.html 50x.html index.html 程序員客棧-領(lǐng)先的程序員自由遠(yuǎn)程工作平臺_files
[root@localhost conf]# systemctl restart nginx.service
我們可以看到訪問的狀態(tài)碼為404分瘦,若想讓狀態(tài)碼變?yōu)?00,就需要修改配置文件
[root@localhost conf]# vim nginx.conf
48 error_page 404 =200 /404.html;
[root@localhost conf]# systemctl restart nginx.service
日志格式
[root@localhost conf]# pwd
/usr/local/nginx/conf
[root@localhost conf]# vim nginx.conf
[root@localhost conf]# systemctl restart nginx.service
17 http {
18 include mime.types;
19 default_type application/octet-stream;
20
21 log_format main '$remote_addr - $remote_user [$time_local] "$request" '
22 '$status $body_bytes_sent "$http_referer" '
23 '"$http_user_agent" "$http_x_forwarded_for"';
24
25 access_log logs/access.log main;
[root@localhost logs]# pwd
/usr/local/nginx/logs
[root@localhost logs]# ls
access.log nginx.pid
[root@localhost logs]# tail -f access.log //查看用戶訪問的日志
192.168.182.1 - - [27/Oct/2021:18:45:57 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36" "-"
日志所對應(yīng)的內(nèi)容
$remote_addr 對應(yīng) 192.168.182.1 訪問的客戶端是什么
$remote_user //這個是nginx的內(nèi)置變量 對應(yīng)第二個 - 就是遠(yuǎn)程主機(jī)使用的哪個遠(yuǎn)程用戶進(jìn)行的訪問
[$time_local] 對應(yīng)的是 [27/Oct/2021:18:45:57 +0800]本地時(shí)間畅卓,這里時(shí)間是中國上海時(shí)間擅腰,+0800表示為東八區(qū)
$request 對應(yīng)的是GET / HTTP/1.1 //GET就是請求服務(wù)器的方法,從服務(wù)器獲取一個資源這個獲取的資源是 "/" 為默認(rèn)首頁 使用http協(xié)議的版本為HTTP/1.1
$status 對應(yīng) 304 //304表示的是客戶端發(fā)出了條件式請求翁潘,但服務(wù)器端發(fā)現(xiàn)客戶端請求的資源已被客戶端緩存過且未發(fā)生改變趁冈,讓客戶端直接到緩存里去取。響應(yīng)狀態(tài)碼為“Not Modified”
$body_bytes_sent 對應(yīng) 0 //表示是放松主體的字節(jié)數(shù)拜马,因?yàn)檫@里使用的是緩存渗勘,所以沒有發(fā)送
$http_referer 對應(yīng) - //表示為是否跳轉(zhuǎn),因?yàn)槲覀兪峭ㄟ^IP進(jìn)行訪問的俩莽,不是跳轉(zhuǎn)是直接訪問的旺坠,所以這個里顯示的是-。跳轉(zhuǎn)就是通過某個網(wǎng)站的主頁扮超,點(diǎn)擊你想要訪問的頁面是跳轉(zhuǎn)取刃,而我們直接通過IP進(jìn)行訪問。
$http_user_agent 對應(yīng) Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36 //表示使用的什么瀏覽器
$http_x_forwarded_for 對應(yīng) - //表示從什么地方跳轉(zhuǎn)過來的出刷,因?yàn)槲覀兪褂肐P進(jìn)行訪問沒有跳轉(zhuǎn)璧疗,所以顯示為-
平滑升級
步驟:
1. 獲取老版本的編譯參數(shù)可以使用 -V來查看
2. 獲取新版本或新功能的軟件包
3. 對新版本的軟件包進(jìn)行編譯,不用安裝
4. 備份老程序
5. 停止老程序并用新程序馁龟,使用老程序的配置文件進(jìn)行啟動
6. 檢驗(yàn)功能崩侠,如果沒有問題就替換老程序使用新程序
實(shí)操
一、
[root@localhost opt]# nginx -V
nginx version: nginx/1.20.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log
二坷檩、軟件包可以去GitHub上下載:https://github.com/openresty/echo-nginx-module
[root@localhost local]# yum -y install unzip
[root@localhost local]# unzip echo-nginx-module-master.zip
三却音、
[root@localhost local]# nginx -V
nginx version: nginx/1.20.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log
[root@localhost nginx-1.20.1]# pwd
/usr/local/nginx-1.20.1
[root@localhost local]# ls
bin etc lib nginx share
echo-nginx-module-master games lib64 nginx-1.20.1 src
echo-nginx-module-master.zip include libexec sbin
[root@localhost nginx-1.20.1]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=../echo-nginx-module-master
[root@localhost nginx-1.20.1]# make
[root@localhost objs]# pwd
/usr/local/nginx-1.20.1/objs
[root@localhost objs]# ls
addon Makefile nginx.8 ngx_auto_headers.h ngx_modules.o
autoconf.err nginx ngx_auto_config.h ngx_modules.c src
四、
[root@localhost nginx-1.20.1]# cp /usr/local/nginx/sbin/nginx /mnt/
五矢炼、
[root@localhost nginx-1.20.1]# systemctl stop nginx.service ; objs/nginx -c /usr/local/nginx/conf/nginx.conf
[root@localhost nginx-1.20.1]# ps -ef | grep nginx
root 37757 1 0 21:13 ? 00:00:00 nginx: master process objs/nginx -c /usr/local/nginx/conf/nginx.conf
nginx 37758 37757 0 21:13 ? 00:00:00 nginx: worker process
root 38249 1203 0 21:13 pts/0 00:00:00 grep --color=auto nginx
六系瓢、
[root@localhost conf]# vim nginx.conf
43 location /abc {
44 echo "hello";
45 }
檢查nginx的語法
[root@localhost nginx-1.20.1]# objs/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost nginx-1.20.1]# objs/nginx -s reload
[root@localhost conf]# curl http://192.168.182.131/abc
hello
覆蓋老配制文件
[root@localhost nginx-1.20.1]# cp objs/nginx /usr/local/nginx/sbin/nginx
cp:是否覆蓋"/usr/local/nginx/sbin/nginx"? y
[root@localhost nginx-1.20.1]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
location區(qū)段句灌,通過指定模式來與客戶端請求的URI相匹配 //location用來定位資源的位置
//功能:允許根據(jù)用戶請求的URI來匹配定義的各location八拱,匹配到時(shí),此請求將被相應(yīng)的location配置塊中的配置所處理涯塔,例如做訪問控制等功能
//語法:location [ 修飾符 ] pattern {......}
常用修飾符說明:
修飾符 | 功能 |
---|---|
= | 精確匹配 |
~ | 正則表達(dá)式模式匹配肌稻,區(qū)分大小寫 |
~* | 正則表達(dá)式模式匹配,不區(qū)分大小寫 |
^~ | 前綴匹配匕荸,類似于無修飾符的行為爹谭,也是以指定模塊開始,不同的是榛搔,如果模式匹配诺凡,那么就停止搜索其他模式了东揣,不支持正則表達(dá)式 |
@ | 定義命名location區(qū)段,這些區(qū)段客戶端不能訪問腹泌,只可以由內(nèi)部產(chǎn)生的請求來訪問嘶卧,如try_files或error_page等 |
沒有使用修飾符前
[root@localhost conf]# curl http://192.168.182.131/abc
hello
[root@localhost conf]# curl http://192.168.182.131/abc/
hello
[root@localhost conf]# curl http://192.168.182.131/abcde
hello
[root@localhost conf]# curl http://192.168.182.131/abcde/
hello
=:表示精確匹配
[root@localhost conf]# vim nginx.conf
48 location = /abc {
49 echo "hello";
50 }
顯示的內(nèi)容如下:
就是只要前三個字符包含abc就可以輸出hello,但是abc后面不能跟類似于"< > | "等具有特殊意義的字符
[root@localhost conf]# curl http://192.168.182.131/abcDB
hello
[root@localhost conf]# curl http://192.168.182.131/abCdb
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
~:表示指定的正則表達(dá)式要區(qū)分大小寫:
[root@localhost conf]# vim nginx.conf
location ~ ^/abc$ {
echo "hello";
}
[root@localhost conf]# nginx -s reload
顯示如下內(nèi)容:
表示的是/abc這個目錄下的內(nèi)容/abc/表示/abc下一級目錄的內(nèi)容凉袱,且要以/abc開頭和結(jié)尾
[root@localhost conf]# curl http://192.168.182.131/abc
hello
[root@localhost conf]# curl http://192.168.182.131/abc?jjyy
hello
[root@localhost conf]# curl http://192.168.182.131/abcu
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
[root@localhost conf]# curl http://192.168.182.131/abc/
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
~*:表示指定的正則表達(dá)式不區(qū)分大小寫
[root@localhost conf]# vim nginx.conf
location ~* ^/abc$ {
echo "hello";
}
[root@localhost conf]# nginx -s reload
顯示如下:
和上面的類似芥吟,只是這個不區(qū)分大小寫
[root@localhost conf]# curl http://192.168.182.131/ABC
hello
[root@localhost conf]# curl http://192.168.182.131/ABCd
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
[root@localhost conf]# curl http://192.168.182.131/ABC/
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
[root@localhost conf]# curl http://192.168.182.131/ABCjjyy
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
~:類似于無修飾符的行為,也是以指定模式開始专甩,不同的是钟鸵,如果模式匹配,則停止搜索其他模式
查找順序和優(yōu)先級:由高到底依次為:
- 帶有=的精確匹配優(yōu)先
- 正則表達(dá)式按照他們在配置文件中定義的順序
- 帶有^~修飾符的涤躲,開頭匹配
- 帶有或*修飾符的态鳖,如果正則表達(dá)式與URI匹配
- 沒有修飾符的精確匹配
優(yōu)先級次序如下:
( location = 路徑 ) --> ( location ^~ 路徑 ) --> ( location ~ 正則 ) --> ( location ~* 正則 ) --> ( location 路徑 )
訪問控制
用于location段
allow:設(shè)定允許哪臺或哪些主機(jī)訪問无虚,多個參數(shù)間用空格隔開
deny:設(shè)定禁止哪臺
示例:
就是除了130和131這兩個IP其余的IP都可以訪問
location / {
deny 192.168.182.130;
deny 192.168.182.131镊靴;
allow 192.168.182.0肌索;
}
[root@localhost test]# pwd
/usr/local/nginx/html/test
[root@localhost html]# mkdir test
[root@localhost html]# cd test/
[root@localhost test]# vim index.html
[root@localhost test]# cat index.html
<html>
<head>
<title>test web</title>
</head>
<a >baidu</a>
</body>
</html>
[root@localhost conf]# vim nginx.conf
location /test {
root html;
index index.html;
[root@localhost conf]# nginx -s reload
[root@localhost conf]# vim nginx.conf
location /test {
deny 192.168.182.1;
root html;
index index.html;
}
[root@localhost conf]# nginx -s reload
本地訪問
[root@localhost test]# curl http://192.168.182.131/test/index.html
<html>
<head>
<title>test web</title>
</head>
<a >baidu</a>
</body>
</html>
讓192.168.182.1網(wǎng)段可以訪問
[root@localhost conf]# vim nginx.conf
location /test {
allow 192.168.182.1;
root html;
index index.html;
}
[root@localhost conf]# nginx -s reload
讓除192.168.182.1之外的網(wǎng)段都無法訪問
[root@localhost conf]# vim nginx.conf
location /test {
allow 192.168.182.1;
deny all;
root html;
index index.html;
}
[root@localhost conf]# nginx -s reload
本地?zé)o法訪問
[root@localhost test]# curl http://192.168.182.131/test/index.html
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
基于用戶認(rèn)證
auth_basic "歡迎信息";
auth_basic_user_file "/path/to/user_auth_file"
user_auth_file內(nèi)容格式為:
username:password
這里的密碼為加密后的密碼串伸但,建議用htpasswd來創(chuàng)建此文件:
htpasswd -c -m /path/to/.user_auth_file USERNAME
[root@localhost conf]# yum -y install httpd-tools
[root@localhost conf]# which htpasswd
/usr/bin/htpasswd
[root@localhost conf]# pwd
/usr/local/nginx/conf
[root@localhost conf]# touch .pass
[root@localhost conf]# htpasswd -c -m .pass admin
New password:
Re-type new password:
Adding password for user admin
[root@localhost conf]# vim nginx.conf
location /test {
auth_basic "hello world";
auth_basic_user_file ".pass";
root html;
index index.html;
}
[root@localhost conf]# nginx -s reload
輸入用戶名和密碼
https配置
生成證書
[root@localhost ~]# mkdir -p /etc/pki/CA
[root@localhost ~]# cd /etc/pki/CA
[root@localhost CA]# mkdir private
[root@localhost CA]# (umask 077;openssl genrsa -out private/cakey.pem 2048)
Generating RSA private key, 2048 bit long modulus
..........................................................................................................................................+++
.........................................+++
e is 65537 (0x10001)
生成自簽署證書
[root@localhost CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 365
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:HB
Locality Name (eg, city) [Default City]:WH
Organization Name (eg, company) [Default Company Ltd]:runtime
Organizational Unit Name (eg, section) []:runtime
Common Name (eg, your name or your server's hostname) []:test.runtime.com
Email Address []:1@2.com
[root@localhost CA]# mkdir certs newcerts crl
[root@localhost CA]# touch index.txt && echo 01 > serial
創(chuàng)建證書存放位置
[root@localhost ~]# mkdir /usr/local/nginx/conf/ssl
[root@localhost ssl]# pwd
/usr/local/nginx/conf/ssl
[root@localhost ssl]# (umask 077;openssl genrsa -out nginx.key 2048)
Generating RSA private key, 2048 bit long modulus
.......+++
.............................+++
e is 65537 (0x10001)
生成證書簽署請求
[root@localhost ssl]# openssl req -new -key nginx.key -days 365 -out nginx.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:HB
Locality Name (eg, city) [Default City]:WH
Organization Name (eg, company) [Default Company Ltd]:runtime
Organizational Unit Name (eg, section) []:runtime
Common Name (eg, your name or your server's hostname) []:test.runtime.com
Email Address []:1@2.com
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@localhost ssl]# ls
nginx.csr nginx.key
修改nginx配置文件
104 server {
105 listen 443 ssl;
106 server_name localhost;
107
108 ssl_certificate ssl/nginx.crt; //修改此行
109 ssl_certificate_key ssl/nginx.key; //修改此行
110
111 ssl_session_cache shared:SSL:1m;
112 ssl_session_timeout 5m;
113
114 ssl_ciphers HIGH:!aNULL:!MD5;
115 ssl_prefer_server_ciphers on;
116
117 location / {
118 root html;
119 index index.html index.htm;
120 }
121 }
CA簽署客戶端提交上來的證書
[root@localhost ssl]# openssl ca -in nginx.csr -out nginx.crt -days 365
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
Serial Number: 1 (0x1)
Validity
Not Before: Oct 28 03:22:40 2021 GMT
Not After : Oct 28 03:22:40 2022 GMT
Subject:
countryName = CN
stateOrProvinceName = HB
organizationName = runtime
organizationalUnitName = runtime
commonName = test.runtime.com
emailAddress = 1@2.com
X509v3 extensions:
X509v3 Basic Constraints:
CA:FALSE
Netscape Comment:
OpenSSL Generated Certificate
X509v3 Subject Key Identifier:
D7:98:3F:0B:01:1F:C2:5D:90:66:91:8C:81:BA:B8:EF:DE:78:6D:13
X509v3 Authority Key Identifier:
keyid:D9:7E:A3:67:BB:F5:DA:BC:6B:A7:A6:47:54:33:0E:7A:60:03:95:71
Certificate is to be certified until Oct 28 03:22:40 2022 GMT (365 days)
Sign the certificate? [y/n]:y
1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
[root@localhost ssl]# nginx -s quit;nginx
開啟狀態(tài)界面
開啟status:
location /status {
stub_status {on | off};
allow 172.16.0.0/16;
deny all;
}
web頁面訪問的方式:http://server_ip/status
狀態(tài)頁面信息詳解:
狀態(tài)碼 | 表示的意義 |
---|---|
Active connections 2 | 當(dāng)前所有處于打開狀態(tài)的連接數(shù) |
accepts | 總共處理了多少個連接 |
handled | 成功創(chuàng)建多少握手 |
requests | 總共處理了多少個請求 |
Reading | nginx讀取到客戶端的Header信息數(shù)夸政,表示正處于接收請求狀態(tài)的連接數(shù) |
Writing | nginx返回給客戶端的Header信息數(shù)逸雹,表示請求已經(jīng)接收完成, |
且正處于處理請求或發(fā)送響應(yīng)的過程中的連接數(shù)
Waiting | 開啟keep-alive的情況下俐镐,這個值等于active - (reading + writing),
意思就是Nginx已處理完正在等候下一次請求指令的駐留連接
配置文件的配置
[root@localhost conf]# vim nginx.conf
location /status {
stub_status on ; //開啟狀態(tài)頁面哺哼,off位關(guān)閉
}
[root@localhost conf]# nginx -s reload
環(huán)境說明:
系統(tǒng) | IP | 服務(wù) |
---|---|---|
Redhat8 | 192.168.182.131 | zabbix_agent+nginx |
redhat8 | 192.168.182.142 | zabbix_server zabbix_agent |
修改代理端的配置文件
[root@localhost scripts]# vim /usr/local/etc/zabbix_agentd.conf
UnsafeUserParameters=1
UserParameter=Waiting,/scripts/Waiting.sh
重啟服務(wù)
[root@localhost ~]# pkill zabbix_agentd
[root@localhost ~]# zabbix_agentd
編寫腳本
[root@localhost scripts]# pwd
/scripts
[root@localhost scripts]# cat Waiting.sh
#!/bin/bash
change=$(curl -s http://192.168.182.131/status | awk 'NR==4 {print $6}')
if [ $change -gt 0 ];then
echo "1"
else
echo "0"
fi
在服務(wù)端測試是否有問題
[root@localhost ~]# zabbix_get -s 192.168.182.131 -k Waiting
0
模擬故障
[root@localhost scripts]# curl -s http://192.168.182.131/status
Active connections: 5
server accepts handled requests
28 28 26
Reading: 0 Writing: 1 Waiting: 4
[root@localhost ~]# zabbix_get -s 192.168.182.131 -k Waiting
1
創(chuàng)建主機(jī)組
創(chuàng)建主機(jī)并添加到主機(jī)組
創(chuàng)建監(jiān)控項(xiàng)
查看最新數(shù)據(jù)
添加觸發(fā)器
手動觸發(fā)并驗(yàn)證
多次訪問192.168.182.131:/status
[root@localhost scripts]# curl -s 192.168.182.131/status
Active connections: 3
server accepts handled requests
106 106 96
Reading: 0 Writing: 1 Waiting: 2
監(jiān)控Reading佩抹、Writing腳本
若想監(jiān)控其他的狀態(tài)可以使用以下腳本
[root@localhost scripts]# cat Reading.sh
#!/bin/bash
sum=$(curl -s http://192.168.182.131/status | awk 'NR==4 {print $2}')
if [ $sum -eq 0 ];then
echo "1"
else
echo "0"
fi
[root@localhost scripts]# cat Writing.sh
#!/bin/bash
Writing=$(curl -s http://192.168.182.131/status | awk 'NR==4 {print $4}')
if [ $Writing -eq 0 ];then
echo "1"
else
echo "0"
fi
rewrite
語法:rewrite regex replacement flag;
如下:
rewrite ^/images/(.*\.jpg)$ /imgs/$1 break
此處的$1用于引用(.*.jpg)匹配到的內(nèi)容,又如:
rewrite ^/bbs/(.*)$ http://www.idfsoft.com/index.html redirect;
[root@localhost images]# pwd
/usr/local/nginx/html/images
[root@localhost html]# ls | grep 1
1.jpg
輸入IP加路徑即可訪問
修改目錄名
[root@localhost html]# mv images imgs
匹配以/images開頭里面任意東西.jpg結(jié)尾的在/imgs/下找
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
location /images {
rewrite ^/images/(.*\.jpg)$ /imgs/$1 break取董;
}
[root@localhost ~]# nginx -s reload
此處的$1用于引用(.*.jpg)匹配到的內(nèi)容棍苹,又如:
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
location /images {
rewrite ^/images/(.*\.jpg)$ http://images.baidu.com break;
}
[root@localhost ~]# nginx -s reload
last用法
location /images {
rewrite ^/images/(.*\.jpg)$ /imgs/$1 last;
}
location /imgs {
rewrite ^/imgs/(.*\.jpg)$ http://images.baidu.com last;
}
[root@localhost ~]# nginx -s reload
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
location /images {
rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;
}
location /imgs {
rewrite ^/imgs/(.*\.jpg)$ http://images.baidu.com last;
}
[root@localhost ~]# nginx -s reload
常見的flag
flag | 作用 |
---|---|
last | 基本上都用這個flag,表示當(dāng)前的匹配結(jié)束茵汰,繼續(xù)下一個匹配枢里,最多匹配10個到20個 |
一旦此rewrite規(guī)則重寫完成后,就不再被后面其它的rewrite規(guī)則進(jìn)行處理
而是由UserAgent重新對重寫后的URL再一次發(fā)起請求蹂午,并從頭開始執(zhí)行類似的過程
break | 中止Rewrite栏豺,不再繼續(xù)匹配
一旦此rewrite規(guī)則重寫完成后,由UserAgent對新的URL重新發(fā)起請求豆胸,
且不再會被當(dāng)前l(fā)ocation內(nèi)的任何rewrite規(guī)則所檢查
redirect | 以臨時(shí)重定向的HTTP狀態(tài)302返回新的URL
permanent | 以永久重定向的HTTP狀態(tài)301返回新的URL
ewrite模塊的作用是用來執(zhí)行URL重定向奥洼。這個機(jī)制有利于去掉惡意訪問的url,也有利于搜索引擎優(yōu)化(SEO)
nginx使用的語法源于Perl兼容正則表達(dá)式(PCRE)庫晚胡,基本語法如下:
標(biāo)識符 | 意義 |
---|---|
^ | 必須以^后的實(shí)體開頭 |
$ | 必須以$前的實(shí)體結(jié)尾 |
. | 匹配任意字符 |
[] | 匹配指定字符集內(nèi)的任意字符 |
[^] | 匹配任何不包括在指定字符集內(nèi)的任意字符串 |
| | 匹配 | 之前或之后的實(shí)體 |
() | 分組灵奖,組成一組用于匹配的實(shí)體嚼沿,通常會有 | 來協(xié)助 |
捕獲子表達(dá)式,可以捕獲放在()之間的任何文本瓷患,比如:
^(hello|sir)$ //字符串為“hi sir”捕獲的結(jié)果:$1=hi$2=sir
//這些被捕獲的數(shù)據(jù)骡尽,在后面就可以當(dāng)變量一樣使用了
if語句
語法:if (condition) {...}
應(yīng)用場景:
- server段
- location段
常見的condition
- 變量名(變量值為空串,或者以“0”開始擅编,則為false攀细,其它的均為true)
- 以變量為操作數(shù)構(gòu)成的比較表達(dá)式(可使用=,!=類似的比較操作符進(jìn)行測試)
- 正則表達(dá)式的模式匹配操作
~:區(qū)分大小寫的模式匹配檢查
~*:不區(qū)分大小寫的模式匹配檢查
!~和!~*:對上面兩種測試取反
- 測試指定路徑為文件的可能性(-f沙咏,!-f)
- 測試指定路徑為目錄的可能性(-d辨图,!-d)
- 測試文件的存在性(-e,!-e)
- 檢查文件是否有執(zhí)行權(quán)限(-x肢藐,!-x)
基于瀏覽器實(shí)現(xiàn)分離案例
if ($http_user_agent ~ Firefox) {
rewrite ^(.*)$ /firefox/$1 break;
}
if ($http_user_agent ~ MSIE) {
rewrite ^(.*)$ /msie/$1 break;
}
if ($http_user_agent ~ Chrome) {
rewrite ^(.*)$ /chrome/$1 break;
}
防盜鏈案例
location ~* \.(jpg|gif|jpeg|png)$ {
valid_referers none blocked www.idfsoft.com;
if ($invalid_referer) {
rewrite ^/ http://www.idfsoft.com/403.html;
}
}