Nginx的配置文件詳解
主配置文件:/usr/local/nginx/conf/nginx.conf
默認(rèn)啟動(dòng)nginx時(shí),使用的配置文件是:安裝路徑/conf/nginx.conf文件
可以在啟動(dòng)nginx時(shí)通過-c選項(xiàng)來指定要讀取的配置文件
nginx常見的配置文件及其作用
配置文件作用
•nginx.conf nginx的基本配置文件
•mime.types MIME類型關(guān)聯(lián)的擴(kuò)展文件
•fastcgi.conf 與fastcgi相關(guān)的配置
•proxy.conf 與proxy相關(guān)的配置
•sites.conf 配置nginx提供的網(wǎng)站,包括虛擬主機(jī)常見的配置文件及其作用
nginx.conf配置詳解
見上篇nginx基礎(chǔ)篇
支持使用變量:
內(nèi)置變量:模塊會(huì)提供內(nèi)建變量定義
自定義變量:set var_name value
用于調(diào)試、定位問題的配置參數(shù)
•daemon {on|off}; //是否以守護(hù)進(jìn)程方式運(yùn)行nginx,調(diào)試時(shí)應(yīng)設(shè)置為off
•master_process {on|off}; //是否以master/worker模型來運(yùn)行nginx,調(diào)試時(shí)可以設(shè)置為off
•error_log 位置 級(jí)別; //配置錯(cuò)誤日志
正常運(yùn)行必備的配置參數(shù)
•user USERNAME [GROUPNAME]; //指定運(yùn)行worker進(jì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)即可
正常運(yùn)行的nginx進(jìn)程如下
[root@nginx ~]# ps -ef | grep nginx
root 37811 1 0 14:22 ? 00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx 37812 37811 0 14:22 ? 00:00:00 nginx: worker process
root 37815 15614 0 14:23 pts/1 00:00:00 vim nginx.conf
root 37845 37821 0 14:23 pts/2 00:00:00 grep --color=auto nginx
修改指定運(yùn)行worker進(jìn)程的用戶后
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
user nobody;
worker_processes 1;
...省略部分
[root@nginx conf]# systemctl restart nginx
[root@nginx ~]# ps -ef | grep nginx
root 37858 1 0 14:26 ? 00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
nobody 37859 37858 0 14:26 ? 00:00:00 nginx: worker process
root 37862 37821 0 14:27 pts/2 00:00:00 grep --color=auto nginx
•pid /path/to/pid_file; //指定nginx守護(hù)進(jìn)程的pid文件[root@nginx ~]# find / -name nginx.pid
•worker_rlimit_nofile number; //設(shè)置所有worker進(jìn)程最大可以打開的文件數(shù),默認(rèn)為1024
優(yōu)化性能的配置參數(shù)
•worker_processes n; //啟動(dòng)n個(gè)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值
top
14:58:02 up 9 min, 3 users, load average: 0.16, 0.10, 0.03
Tasks: 171 total, 1 running, 170 sleeping, 0 stopped, 0 zombie
%Cpu(s): 0.0 us, 0.1 sy, 0.0 ni, 99.9 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
MiB Mem : 3709.6 total, 3260.0 free, 219.1 used, 230.5 buff/cache
MiB Swap: 2048.0 total, 2048.0 free, 0.0 used. 3264.8 avAIl Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND P
1649 nobody 20 0 114308 6232 4652 S 0.0 0.2 0:00.00 nginx 1
1650 root 20 0 0 0 0 I 0.0 0.0 0:00.06 kworke+ 3
1651 root 20 0 0 0 0 I 0.0 0.0 0:00.00 kworke+ 3
1653 root 20 0 65428 4436 3772 R 0.0 0.1 0:00.07 top 3
1654 root 20 0 0 0 0 I 0.0 0.0 0:00.00 kworke+ 0
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
user nobody;
worker_processes 2;
worker_cpu_affinity 01 10;
[root@nginx ~]# systemctl restart nginx
top
14:56:02 up 7 min, 3 users, load average: 0.03, 0.03, 0.00
Tasks: 169 total, 1 running, 168 sleeping, 0 stopped, 0 zombie
%Cpu(s): 0.1 us, 0.1 sy, 0.0 ni, 99.8 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
MiB Mem : 3709.6 total, 3259.6 free, 219.5 used, 230.5 buff/cache
MiB Swap: 2048.0 total, 2048.0 free, 0.0 used. 3264.3 avail Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND P
1634 nobody 20 0 114228 5840 4516 S 0.0 0.2 0:00.00 nginx 0
1635 nobody 20 0 114228 5840 4516 S 0.0 0.2 0:00.00 nginx 1
1636 root 20 0 0 0 0 I 0.0 0.0 0:00.01 kworke+ 0
1638 root 20 0 65428 4496 3832 R 0.0 0.1 0:00.11 top 3
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
user nobody;
worker_rlimit_nofile 65535;
worker_priority -10;
[root@nginx ~]# systemctl restart nginx
[root@nginx ~]# ps -elf | grep nginx
1 S root 1695 1 0 80 0 - 20407 - 15:04 ? 00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
5 S nobody 1696 1695 0 70 -10 - 28555 do_epo 15:04 ? 00:00:00 nginx: worker process
0 S root 1698 1591 0 80 0 - 3034 - 15:04 pts/1 00:00:00 grep --color=auto nginx
事件相關(guān)的配置:(event{}段中的配置參數(shù))
•accept_mutex {off|on}; //master調(diào)度用戶請(qǐng)求至各worker進(jìn)程時(shí)使用的負(fù)載均衡鎖;on表示能讓多個(gè)worker輪流地、序列化地去響應(yīng)新請(qǐng)求-
•lock_file file; //accept_mutex用到的互斥鎖鎖文件路徑
•use [epoll | rtsig | select | poll]; //指明使用的事件模型,建議讓nginx自行選擇
•worker_connections #; //每個(gè)進(jìn)程能夠接受的最大連接數(shù)
網(wǎng)絡(luò)連接相關(guān)的配置參數(shù)
•keepalive_timeout number; //長(zhǎng)連接的超時(shí)時(shí)長(zhǎng),默認(rèn)為65s
•keepalive_requests number; //在一個(gè)長(zhǎng)連接上所能夠允許請(qǐng)求的最大資源數(shù)
•keepalive_disable [msie6|safari|none]; //為指定類型的UserAgent禁用長(zhǎng)連接
•tcp_nodelay on|off; //是否對(duì)長(zhǎng)連接使用TCP_NODELAY選項(xiàng),為了提升用戶體驗(yàn),通常設(shè)為on
•client_header_timeout number; //讀取http請(qǐng)求報(bào)文首部的超時(shí)時(shí)長(zhǎng)
•client_body_timeout number; //讀取http請(qǐng)求報(bào)文body部分的超時(shí)時(shí)長(zhǎng)
•send_timeout number; //發(fā)送響應(yīng)報(bào)文的超時(shí)時(shí)長(zhǎng)
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
作為web服務(wù)器時(shí)使用的配置:(http{}段的配置參數(shù))
由ngx_http_core_module模塊引入。
nginx的HTTP配置主要包括四個(gè)區(qū)塊,結(jié)構(gòu)如下
http { //協(xié)議級(jí)別
include mime.types;
default_type Application/octet-stream;
keepalive_timeout 65;
gzip on;
upstream {//負(fù)載均衡配置
…
}
server {//服務(wù)器級(jí)別,每個(gè)server類似于httpd中的一個(gè)
listen 80; //監(jiān)聽端口
server_name localhost; //域名
location / {//請(qǐng)求級(jí)別,類似于httpd中的,用于定義URL與本地文件系統(tǒng)的映射關(guān)系
root html;
index index.html index.htm;
}
}
}
listen:指定監(jiān)聽的地址和端
listen address[:port];
listen port;
server_name NAME […]; 后面可跟多個(gè)主機(jī),名稱可使用正則表達(dá)式或通配符
當(dāng)有多個(gè)server時(shí),匹配順序如下:
1.先做精確匹配檢查
2.左側(cè)通配符匹配檢查,如.test.com
3.右側(cè)通配符匹配檢查,如mail.
4.正則表達(dá)式匹配檢查,如~ ^.*.test.com$
default_server
•root path; 設(shè)置資源路徑映射,用于指明請(qǐng)求的URL所對(duì)應(yīng)的資源所在的文件系統(tǒng)上的起始路徑
•alias path; 用于location配置段,定義路徑別名
•index file; 默認(rèn)主頁面
•index index.php index.html;
error_page code […] [=code] URI | @name
根據(jù)http響應(yīng)狀態(tài)碼來指明特用的錯(cuò)誤頁面,例如 error_page 404 /404_customed.html
[=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 detailed_format '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$host" "$request_time" "$upstream_addr" '
'"$upstream_status" "$http_x_forwarded_for"';
解釋:
•$remote_addr: 客戶端的 IP 地址。
•$remote_user: 遠(yuǎn)程用戶身份,通常為空。
•[$time_local]: 請(qǐng)求發(fā)生的本地時(shí)間。
•"$request": 包括請(qǐng)求方法、請(qǐng)求 URI 和 HTTP 協(xié)議版本。
•$status: 服務(wù)器響應(yīng)的 HTTP 狀態(tài)碼。
•$body_bytes_sent: 發(fā)送給客戶端的響應(yīng)主體字節(jié)數(shù)。
•"$http_referer": 引薦頁面的 URL。
•"$http_user_agent": 用戶代理信息,即客戶端瀏覽器或應(yīng)用的標(biāo)識(shí)信息。
•"$host": 請(qǐng)求中的主機(jī)頭,標(biāo)識(shí)了請(qǐng)求的目標(biāo)主機(jī)名。
•"$request_time": 請(qǐng)求處理時(shí)間,通常以秒為單位。
•"$upstream_addr": Nginx 作為反向代理時(shí),它連接到的上游服務(wù)器的地址。
•"$upstream_status": 從上游服務(wù)器接收到的 HTTP 狀態(tài)碼。
•"$http_x_forwarded_for": X-Forwarded-For 頭,包含了客戶端 IP 地址,如果通過代理的話。
當(dāng)顯示錯(cuò)誤頁面報(bào)錯(cuò)404時(shí),調(diào)轉(zhuǎn)為自定義的公益界面
[root@host ~]# vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location /test {
root html;
index index.html index.htm;
}
error_page 404 /404.html;
[root@host ~]# cd /usr/local/nginx/html/
[root@host html]# mv test/ 404.html
[root@host ~]# systemctl restart nginx
location段
通過指定模式來與客戶端請(qǐng)求的URI相匹配
功能:允許根據(jù)用戶請(qǐng)求的URI來匹配定義的各location,匹配到時(shí),此請(qǐng)求將被相應(yīng)的location配置塊中的配置所處理,例如做訪問控制等功能
語法:location [ 修飾符 ] pattern {......}
常用修飾符:
= 精確匹配
~ 正則表達(dá)式模式匹配,區(qū)分大小寫
~* 正則表達(dá)式模式匹配,不區(qū)分大小寫
^~ 前綴匹配,類似于無修飾符的行為,也是以指定模塊開始,不同的是,如果模式匹配,那么就停止搜索其他模式了,不支持正則表達(dá)式
@ 定義命名location區(qū)段,這些區(qū)段客戶端不能訪問,只可以由內(nèi)部產(chǎn)生的請(qǐng)求來訪問,如try_files或error_page等
[root@host ~]# vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location = / {
echo "[ Test A]";
}
location / {
echo "[ Test B]";
}
location = /documents {
echo "[ Test C]";
}
location = ^~ /images/ {
echo "[ Test D]";
}
location = ~* .(gif|jpg|jpeg)$ {
echo "[ Test E]";
}
[root@host conf]# curl 192.168.0.100
[ TestA]
[root@host conf]# curl 192.168.0.100/asdlnasjkd asklwqeq
[ TestB]
[root@host conf]# curl 192.168.0.100/documents
[ TestC]
[root@host conf]# curl 192.168.0.100//documents/asiodaskjdaskldnaskdbasjkdnlqwd
[ TestC]
[root@host conf]# curl 192.168.0.100/images/1.gif
[ TestD]
[root@host conf]# curl 192.168.0.100//documents/1.jpg
[ TestE]
沒有修飾符表示必須以指定模式開始
[root@host ~]# vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name localhost;
[root@host ~]# systemctl restart nginx
那么如下內(nèi)容就可正確匹配:
[root@host ~]# curl 192.168.0.100/abc/
hello world
[root@host ~]# curl 192.168.0.100/abc?salkjsnskDNS93jskdndsfs
hello world
[root@host ~]# curl 192.168.0.100/abc
hello world
•=:表示必須與指定的模式精確匹配
[root@host ~]# vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location /abc {
echo "hello world";
}
location / {
echo "123";
}
[root@host ~]# curl 192.168.0.100/abc
hello world
[root@host ~]# curl 192.168.0.100/abc/
123
[root@host ~]# curl 192.168.0.100/saddassda
123
–~:表示指定的正則表達(dá)式要區(qū)分大小寫,如
[root@host vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location /abc {
echo "hello world";
}
location ~ ^/abc$ {
echo "xixixi";
}
location / {
echo "hehe";
}
[root@host ~]# curl 192.168.0.100/abc
xixixi
[root@host ~]# curl 192.168.0.100/abcde
hello world
[root@host ~]# curl 192.168.0.100/ABC
hehe
•~*:表示指定的正則表達(dá)式不區(qū)分大小寫
[root@host ~]# vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location /abc {
echo "hello world";
}
location ~* ^/abc$ {
echo "2222";
}
location / {
echo "3333";
}
[root@host ~]# curl 192.168.0.100/abc
2222
[root@host ~]# curl 192.168.0.100/ABC
2222
•~:類似于無修飾符的行為,也是以指定模式開始,不同的是,如果模式匹配,則停止搜索其他模式
查找順序和優(yōu)先級(jí):由高到底依次為
1.帶有=的精確匹配優(yōu)先
2.正則表達(dá)式按照他們?cè)谂渲梦募卸x的順序
3.帶有^~修飾符的,開頭匹配
4.帶有~或~*修飾符的,如果正則表達(dá)式與URI匹配
5.沒有修飾符的精確匹配
優(yōu)先級(jí)次序如下:
( location = 路徑 ) --> ( location ^~ 路徑 ) --> ( location ~ 正則 ) --> ( location ~* 正則 ) --> ( location 路徑 )
訪問控制
用于location段
•allow:設(shè)定允許哪臺(tái)或哪些主機(jī)訪問,多個(gè)參數(shù)間用空格隔開
•deny:設(shè)定禁止哪臺(tái)或哪些主機(jī)訪問,多個(gè)參數(shù)間用空格隔開
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name localhost;
location / {
deny 192.168.0.100/32;
echo "hehehe";
}
[root@nginx ~]# systemctl restart nginx
[root@nginx ~]# curl 192.168.0.100
vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name localhost;
location /abc {
deny all;
echo "1111"
}
location ~* ^/abc$ {
allow 192.168.0.100/32;
echo "22222
}
[root@nginx ~]# curl 192.168.0.100/abc
22222
基于用戶認(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@nginx ~]# yum -y install httpd-tools
[root@nginx ~]# htpasswd -c -m /usr/local/nginx/conf/.htpasswd test
New password:
Re-type new password:
Adding password for user test
[root@nginx ~]# cat /usr/local/nginx/conf/.htpasswd
test:$apr1$widaKKMg$KkKj4hXFizBF2/Fb89fP.0
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name localhost;
location / {
auth_basic "yexiaotian";
auth_basic_user_file "/usr/local/nginx/conf/.htpasswd";
echo "hehehe";
}
https配置
生成私鑰,生成證書簽署請(qǐng)求并獲得證書
CA生成一對(duì)密鑰
[root@nginx ~]# mkdir -p /etc/pki/CA
[root@nginx ~]# cd /etc/pki/CA/
[root@nginx CA]# mkdir private
[root@nginx CA]# ls
private
[root@nginx CA]# (umask 077;openssl genrsa -out private/cakey.pem 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
........................................+++++
.........................................................................+++++
e is 65537 (0x010001)
[root@nginx CA]# ls private/
cakey.pem
[root@nginx CA]# mkdir certs newcerts crl
[root@nginx CA]# touch index.txt && echo 01 > serial
CA生成自簽署證書
[root@nginx 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]:www.test.com
Organizational Unit Name (eg, section) []:www.test.com
Common Name (eg, your name or your server's hostname) []:www.test.com
Email Address []:123@123.com
[root@nginx CA]# ls
cacert.pem private
[root@nginx CA]# mkdir certs newcerts crl
[root@nginx CA]# touch index.txt && echo 01 > serial
客戶端生成密鑰
[root@nginx ~]# cd /usr/local/nginx/
[root@nginx nginx]# mkdir ssl
[root@nginx nginx]# cd ssl
[root@nginx ssl]# (umask 077;openssl genrsa -out nginx.key 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
................................................................+++++
....................................+++++
e is 65537 (0x010001)
[root@nginx ssl]# ls
nginx.key
客戶端生成證書簽署請(qǐng)求
[root@nginx ssl]# openssl req -new -key nginx.key -days 365 -out nginx.csr
Ignoring -days; not generating a certificate
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]:www.test.com
Organizational Unit Name (eg, section) []:www.test.com
Common Name (eg, your name or your server's hostname) []:www.test.com
Email Address []:123@123.com
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@nginx ssl]# ls
nginx.csr nginx.key
CA簽署客戶端提交上來的證書
[root@nginx 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 13 07:37:16 2022 GMT
Not After : Oct 13 07:37:16 2023 GMT
Subject:
countryName = CN
stateOrProvinceName = HB
organizationName = www.test.com
organizationalUnitName = www.test.com
commonName = www.test.com
emailAddress = 1@2.com
X509v3 extensions:
X509v3 Basic Constraints:
CA:FALSE
 .NETscape Comment:
OpenSSL Generated Certificate
X509v3 Subject Key Identifier:
23:E2:E9:C3:74:34:F8:2E:10:9E:F2:FF:32:9A:0E:E4:A8:6C:45:02
X509v3 Authority Key Identifier:
keyid:A3:97:92:68:D9:9C:70:86:E7:55:F7:E4:2C:68:B9:6A:3B:FA:62:9E
Certificate is to be certified until Oct 13 07:37:16 2023 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@nginx ssl]# rm -rf nginx.csr
[root@nginx ssl]# ls
nginx.crt nginx.key
然后在nginx.conf中配置如下內(nèi)容:
server {
listen 443 ssl;
server_name www.test.com;
ssl_certificate /usr/local/nginx/ssl/nginx.crt;
ssl_certificate_key /usr/local/nginx/ssl/nginx.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
root html;
index index.html index.htm;
}
}
[root@nginx conf]# systemctl restart nginx
[root@nginx conf]# netstat -anlp
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 0.0.0.0:443 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
開啟狀態(tài)界面
開啟status:
格式:
location /status {
stub_status {on | off};
allow 172.16.0.0/16;
deny all;
}
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location = /status{
stub_status;
}
[root@nginx conf]# systemctl restart nginx
[root@nginx ssl]# curl 192.168.0.100/status
Active connections: 3
server accepts handled requests
3 3 3
Reading: 0 Writing: 1 Waiting: 2
狀態(tài)頁面信息詳解:
•Active connections 2 當(dāng)前所有處于打開狀態(tài)的連接數(shù)
•accepts 總共處理了多少個(gè)連接
•handled 成功創(chuàng)建多少握手
•requests 總共處理了多少個(gè)請(qǐng)求
•Reading nginx讀取到客戶端的Header信息數(shù),表示正處于接收請(qǐng)求狀態(tài)的連接數(shù)
•Writing nginx返回給客戶端的Header信息數(shù),表示請(qǐng)求已經(jīng)接收完成,且正處于處理請(qǐng)求或發(fā)送響應(yīng)的過程中的連接數(shù)
•Waiting 開啟keep-alive的情況下,這個(gè)值等于active - (reading + writing),意思就是Nginx已處理完正在等候下一次請(qǐng)求指令的駐留連接
rewrite
語法:rewrite regex replacement flag; eg:
rewrite ^/images/(.*.jpg)$ /imgs/$1 break;
eg1:
上傳一張圖片
[root@nginx ~]# cd /usr/local/nginx/html/
[root@nginx html]# mkdir images
[root@nginx html]# cd images/
[root@nginx images]# ls
test.jpg
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
location / {
root html;
index index.html index.htm;
}
location /images {
root html;
index index.html index.htm;
}
當(dāng)我們改變路徑,使用rewrite進(jìn)行重定向,也能匹配到
[root@nginx html]# mv images/ imgs
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
location / {
root html;
index index.html index.htm;
}
location /images {
rewrite ^/images/(.*.jpg)$ /imgs/$1 break;
}
此處的$1用于引用(.*.jpg)匹配到的內(nèi)容
eg2:
rewrite ^/bbs/(.*)$ http://www.test.com/index.html redirect;
replacement可以是某個(gè)路徑,也可以是某個(gè)URL
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
location / {
root html;
index index.html index.htm;
}
location /images {
rewrite ^/images/(.*.jpg)$ https://scpic.chinaz.net/files/pic/pic9/202009/apic27858.jpg break;
}
[root@nginx ~]# systemctl restart nginx
常見的flag
•flag 作用
•last 基本上都用這個(gè)flag,表示當(dāng)前的匹配結(jié)束,繼續(xù)下一個(gè)匹配,最多匹配10個(gè)到20個(gè)一旦此rewrite規(guī)則重寫完成后,就不再被后面其它的rewrite規(guī)則進(jìn)行處理而是由UserAgent重新對(duì)重寫后的URL再一次發(fā)起請(qǐng)求,并從頭開始執(zhí)行類似的過程
•break 中止Rewrite,不再繼續(xù)匹配一旦此rewrite規(guī)則重寫完成后,由UserAgent對(duì)新的URL重新發(fā)起請(qǐng)求,且不再會(huì)被當(dāng)前l(fā)ocation內(nèi)的任何rewrite規(guī)則所檢查
•redirect 以臨時(shí)重定向的HTTP狀態(tài)302返回新的URL
•permanent 以永久重定向的HTTP狀態(tài)301返回新的URL
•rewrite模塊的作用是用來執(zhí)行URL重定向。這個(gè)機(jī)制有利于去掉惡意訪問的url,也有利于搜索引擎優(yōu)化(seo)
nginx使用的語法源于Perl兼容正則表達(dá)式(PCRE)庫(kù),
基本語法:
^ 必須以^后的實(shí)體開頭
$ 必須以$前的實(shí)體結(jié)尾
. 匹配任意字符
[] 匹配指定字符集內(nèi)的任意字符
[^] 匹配任何不包括在指定字符集內(nèi)的任意字符串
| 匹配 |之前或之后的實(shí)
() 分組,組成一組用于匹配的實(shí)體,通常會(huì)有
^(hello|sir)$ //字符串為“hi sir”捕獲的結(jié)果:$1=hi$2=sir
這些被捕獲的數(shù)據(jù),在后面就可以當(dāng)變量一樣使用了
if
語法:if (condition) {…}
應(yīng)用場(chǎng)景:
server段
location段
常見的condition
變量名(變量值為空串,或者以“0”開始,則為false,其它的均為true)以變量為操作數(shù)構(gòu)成的比較表達(dá)式(可使用=,!=類似的比較操作符進(jìn)行測(cè)試)
正則表達(dá)式的模式匹配操作
•~:區(qū)分大小寫的模式匹配檢查
•~:不區(qū)分大小寫的模式匹配檢查
•!~和 !~:對(duì)上面兩種測(cè)試取反
•測(cè)試指定路徑為文件的可能性(-f,!-f)
•測(cè)試指定路徑為目錄的可能性(-d,!-d)
•測(cè)試文件的存在性(-e,!-e)
•檢查文件是否有執(zhí)行權(quán)限(-x,!-x)
eg:
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;
}
防盜鏈案例
HTTP Referer是header的一部分,當(dāng)瀏覽器向web服務(wù)器發(fā)送請(qǐng)求的時(shí)候,一般會(huì)帶上Referer,告訴服務(wù)器我是從哪個(gè)頁面鏈接過來的,服務(wù)器籍此可以獲得一些信息用于處理。比如從我主頁上鏈接到一個(gè)朋友那里,他的服務(wù)器就能夠從HTTP Referer中統(tǒng)計(jì)出每天有多少用戶點(diǎn)擊我主頁上的鏈接訪問他的網(wǎng)站
本次請(qǐng)求的引用頁是誰,資源提供端可以分析這個(gè)引用者是否“友好”,是否允許其“引用”,對(duì)于不允許訪問的引用者,可以不提供圖片,這樣訪問者在頁面上就只能看到一個(gè)圖片無法加載的瀏覽器默認(rèn)占位的警告圖片,甚至服務(wù)端可以返回一個(gè)默認(rèn)的提醒勿盜鏈的提示圖片。
一般的站點(diǎn)或者靜態(tài)資源托管站點(diǎn)都提供防盜鏈的設(shè)置,也就是讓服務(wù)端識(shí)別指定的Referer,在服務(wù)端接收到請(qǐng)求時(shí),通過匹配referer頭域與配置,對(duì)于指定放行,對(duì)于其他referer視為盜鏈。
一句話概括就是
"通過判斷request請(qǐng)求頭的refer是否來源于本站"
location ~* .(jpg|gif|jpeg|png)$ {
valid_referers none blocked www.test.com;
if ($invalid_referer) {
rewrite ^/ http://www.test.com/403.html;
}
}