日日操夜夜添-日日操影院-日日草夜夜操-日日干干-精品一区二区三区波多野结衣-精品一区二区三区高清免费不卡

公告:魔扣目錄網為廣大站長提供免費收錄網站服務,提交前請做好本站友鏈:【 網站目錄:http://www.ylptlb.cn 】, 免友鏈快審服務(50元/站),

點擊這里在線咨詢客服
新站提交
  • 網站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

Nginx的配置文件詳解

主配置文件:/usr/local/nginx/conf/nginx.conf

默認啟動nginx時,使用的配置文件是:安裝路徑/conf/nginx.conf文件            
可以在啟動nginx時通過-c選項來指定要讀取的配置文件            
nginx常見的配置文件及其作用

配置文件作用

•nginx.conf nginx的基本配置文件

•mime.types MIME類型關聯的擴展文件

•fastcgi.conf 與fastcgi相關的配置

•proxy.conf 與proxy相關的配置

•sites.conf 配置nginx提供的網站,包括虛擬主機常見的配置文件及其作用

nginx.conf配置詳解

見上篇nginx基礎篇

支持使用變量:

內置變量:模塊會提供內建變量定義              
自定義變量:set var_name value

用于調試、定位問題的配置參數

•daemon {on|off}; //是否以守護進程方式運行nginx,調試時應設置為off

•master_process {on|off}; //是否以master/worker模型來運行nginx,調試時可以設置為off

•error_log 位置 級別; //配置錯誤日志              
             全網最詳細nginx配置詳解

正常運行必備的配置參數

•user USERNAME [GROUPNAME]; //指定運行worker進程的用戶和組

•pid /path/to/pid_file; //指定nginx守護進程的pid文件

•worker_rlimit_nofile number; //設置所有worker進程最大可以打開的文件數,默認為1024

•worker_rlimit_core size; //指明所有worker進程所能夠使用的總體的最大核心文件大小,保持默認即可

               

正常運行的nginx進程如下

[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

修改指定運行worker進程的用戶后

[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守護進程的pid文件[root@nginx ~]# find / -name nginx.pid

•worker_rlimit_nofile number; //設置所有worker進程最大可以打開的文件數,默認為1024

優化性能的配置參數

•worker_processes n; //啟動n個worker進程,這里的n為了避免上下文切換,通常設置為cpu總核心數-1或等于總核心數

•worker_cpu_affinity cpumask …; //將進程綁定到某cpu中,避免頻繁刷新緩存

//cpumask:使用8位二進制表示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; //計時器解析度。降低此值,可減少gettimeofday()系統調用的次數

•worker_priority number; //指明worker進程的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

事件相關的配置:(event{}段中的配置參數)

•accept_mutex {off|on}; //master調度用戶請求至各worker進程時使用的負載均衡鎖;on表示能讓多個worker輪流地、序列化地去響應新請求-

•lock_file file; //accept_mutex用到的互斥鎖鎖文件路徑

•use [epoll | rtsig | select | poll]; //指明使用的事件模型,建議讓nginx自行選擇

•worker_connections #; //每個進程能夠接受的最大連接數

網絡連接相關的配置參數

•keepalive_timeout number; //長連接的超時時長,默認為65s

•keepalive_requests number; //在一個長連接上所能夠允許請求的最大資源數

•keepalive_disable [msie6|safari|none]; //為指定類型的UserAgent禁用長連接

•tcp_nodelay on|off; //是否對長連接使用TCP_NODELAY選項,為了提升用戶體驗,通常設為on

•client_header_timeout number; //讀取http請求報文首部的超時時長

•client_body_timeout number; //讀取http請求報文body部分的超時時長

•send_timeout number; //發送響應報文的超時時長

fastcgi的相關配置參數

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;              
}

常需要進行調整的參數

•worker_processes

•worker_connections

•worker_cpu_affinity

•worker_priority

作為web服務器時使用的配置:(http{}段的配置參數)

由ngx_http_core_module模塊引入。

nginx的HTTP配置主要包括四個區塊,結構如下

http {  //協議級別              
  include mime.types;              
  default_type Application/octet-stream;              
  keepalive_timeout 65;              
  gzip on;              
  upstream {//負載均衡配置              
  …              
  }              
  server {//服務器級別,每個server類似于httpd中的一個              
   listen 80;  //監聽端口              
    server_name localhost; //域名              
    location / {//請求級別,類似于httpd中的,用于定義URL與本地文件系統的映射關系              
      root html;               
     index index.html index.htm;              
   }              
  }              
}              
listen:指定監聽的地址和端              
listen address[:port];              
listen port;              
server_name NAME […]; 后面可跟多個主機,名稱可使用正則表達式或通配符

當有多個server時,匹配順序如下:              
1.先做精確匹配檢查              
2.左側通配符匹配檢查,如.test.com              
3.右側通配符匹配檢查,如mail.              
4.正則表達式匹配檢查,如~ ^.*.test.com$

default_server

•root path; 設置資源路徑映射,用于指明請求的URL所對應的資源所在的文件系統上的起始路徑

•alias path; 用于location配置段,定義路徑別名

•index file; 默認主頁面

•index index.php index.html;

error_page code […] [=code] URI | @name

根據http響應狀態碼來指明特用的錯誤頁面,例如 error_page 404 /404_customed.html

[=code]: 以指定的響應碼進行響應,而不是默認的原來的響應,默認表示以新資源的響應碼為其響應碼,例如 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: 遠程用戶身份,通常為空。

•[$time_local]: 請求發生的本地時間。

•"$request": 包括請求方法、請求 URI 和 HTTP 協議版本。

•$status: 服務器響應的 HTTP 狀態碼。

•$body_bytes_sent: 發送給客戶端的響應主體字節數。

•"$http_referer": 引薦頁面的 URL。

•"$http_user_agent": 用戶代理信息,即客戶端瀏覽器或應用的標識信息。

•"$host": 請求中的主機頭,標識了請求的目標主機名。

•"$request_time": 請求處理時間,通常以秒為單位。

•"$upstream_addr": Nginx 作為反向代理時,它連接到的上游服務器的地址。

•"$upstream_status": 從上游服務器接收到的 HTTP 狀態碼。

•"$http_x_forwarded_for": X-Forwarded-For 頭,包含了客戶端 IP 地址,如果通過代理的話。

當顯示錯誤頁面報錯404時,調轉為自定義的公益界面

             

[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段

通過指定模式來與客戶端請求的URI相匹配

功能:允許根據用戶請求的URI來匹配定義的各location,匹配到時,此請求將被相應的location配置塊中的配置所處理,例如做訪問控制等功能

語法:location [ 修飾符 ] pattern {......}

常用修飾符:

=           精確匹配              
~           正則表達式模式匹配,區分大小寫              
~*           正則表達式模式匹配,不區分大小寫              
^~           前綴匹配,類似于無修飾符的行為,也是以指定模塊開始,不同的是,如果模式匹配,那么就停止搜索其他模式了,不支持正則表達式              
@           定義命名location區段,這些區段客戶端不能訪問,只可以由內部產生的請求來訪問,如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              
那么如下內容就可正確匹配:              
[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

–~:表示指定的正則表達式要區分大小寫,如

[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

•~*:表示指定的正則表達式不區分大小寫

[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

             

•~:類似于無修飾符的行為,也是以指定模式開始,不同的是,如果模式匹配,則停止搜索其他模式

查找順序和優先級:由高到底依次為

1.帶有=的精確匹配優先

2.正則表達式按照他們在配置文件中定義的順序

3.帶有^~修飾符的,開頭匹配

4.帶有~或~*修飾符的,如果正則表達式與URI匹配

5.沒有修飾符的精確匹配

優先級次序如下:

( location = 路徑 ) --> ( location ^~ 路徑 ) --> ( location ~ 正則 ) --> ( location ~* 正則 ) --> ( location 路徑 )

訪問控制

用于location段

•allow:設定允許哪臺或哪些主機訪問,多個參數間用空格隔開

•deny:設定禁止哪臺或哪些主機訪問,多個參數間用空格隔開

[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

基于用戶認證

•auth_basic "歡迎信息";

•auth_basic_user_file "/path/to/user_auth_file"

 user_auth_file內容格式為:username:password (這里的密碼為加密后的密碼串,建議用htpasswd來創建此文件)

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配置

生成私鑰,生成證書簽署請求并獲得證書

CA生成一對密鑰

[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 []:[email protected]              
[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

客戶端生成證書簽署請求

[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 []:[email protected]              
             
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              = [email protected]              
        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中配置如下內容:

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               [::]:*  

開啟狀態界面

開啟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

狀態頁面信息詳解:

•Active connections 2 當前所有處于打開狀態的連接數

•accepts 總共處理了多少個連接

•handled 成功創建多少握手

•requests 總共處理了多少個請求

•Reading nginx讀取到客戶端的Header信息數,表示正處于接收請求狀態的連接數

•Writing nginx返回給客戶端的Header信息數,表示請求已經接收完成,且正處于處理請求或發送響應的過程中的連接數

•Waiting 開啟keep-alive的情況下,這個值等于active - (reading + writing),意思就是Nginx已處理完正在等候下一次請求指令的駐留連接

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;              
        }              

當我們改變路徑,使用rewrite進行重定向,也能匹配到

[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)匹配到的內容

eg2:

rewrite ^/bbs/(.*)$ http://www.test.com/index.html redirect;

replacement可以是某個路徑,也可以是某個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 基本上都用這個flag,表示當前的匹配結束,繼續下一個匹配,最多匹配10個到20個一旦此rewrite規則重寫完成后,就不再被后面其它的rewrite規則進行處理而是由UserAgent重新對重寫后的URL再一次發起請求,并從頭開始執行類似的過程

•break 中止Rewrite,不再繼續匹配一旦此rewrite規則重寫完成后,由UserAgent對新的URL重新發起請求,且不再會被當前location內的任何rewrite規則所檢查

•redirect 以臨時重定向的HTTP狀態302返回新的URL

•permanent 以永久重定向的HTTP狀態301返回新的URL

•rewrite模塊的作用是用來執行URL重定向。這個機制有利于去掉惡意訪問的url,也有利于搜索引擎優化(seo)

nginx使用的語法源于Perl兼容正則表達式(PCRE)庫,

基本語法:

^           必須以^后的實體開頭              
$           必須以$前的實體結尾              
.           匹配任意字符              
[]           匹配指定字符集內的任意字符              
[^]           匹配任何不包括在指定字符集內的任意字符串              
|           匹配 |之前或之后的實              
()           分組,組成一組用于匹配的實體,通常會有              
^(hello|sir)$       //字符串為“hi sir”捕獲的結果:$1=hi$2=sir

這些被捕獲的數據,在后面就可以當變量一樣使用了

if

語法:if (condition) {…}

應用場景:

server段              
location段              
常見的condition

變量名(變量值為空串,或者以“0”開始,則為false,其它的均為true)以變量為操作數構成的比較表達式(可使用=,!=類似的比較操作符進行測試)              
正則表達式的模式匹配操作

•~:區分大小寫的模式匹配檢查

•~:不區分大小寫的模式匹配檢查

•!~和 !~:對上面兩種測試取反

•測試指定路徑為文件的可能性(-f,!-f)

•測試指定路徑為目錄的可能性(-d,!-d)

•測試文件的存在性(-e,!-e)

•檢查文件是否有執行權限(-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的一部分,當瀏覽器向web服務器發送請求的時候,一般會帶上Referer,告訴服務器我是從哪個頁面鏈接過來的,服務器籍此可以獲得一些信息用于處理。比如從我主頁上鏈接到一個朋友那里,他的服務器就能夠從HTTP Referer中統計出每天有多少用戶點擊我主頁上的鏈接訪問他的網站

本次請求的引用頁是誰,資源提供端可以分析這個引用者是否“友好”,是否允許其“引用”,對于不允許訪問的引用者,可以不提供圖片,這樣訪問者在頁面上就只能看到一個圖片無法加載的瀏覽器默認占位的警告圖片,甚至服務端可以返回一個默認的提醒勿盜鏈的提示圖片。

一般的站點或者靜態資源托管站點都提供防盜鏈的設置,也就是讓服務端識別指定的Referer,在服務端接收到請求時,通過匹配referer頭域與配置,對于指定放行,對于其他referer視為盜鏈。

一句話概括就是              
"通過判斷request請求頭的refer是否來源于本站"

location ~* .(jpg|gif|jpeg|png)$ {              
  valid_referers none blocked www.test.com;              
  if ($invalid_referer) {              
    rewrite ^/ http://www.test.com/403.html;              
  }              
}

分享到:
標簽:nginx
用戶無頭像

網友整理

注冊時間:

網站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網站吧!
最新入駐小程序

數獨大挑戰2018-06-03

數獨一種數學游戲,玩家需要根據9

答題星2018-06-03

您可以通過答題星輕松地創建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學四六

運動步數有氧達人2018-06-03

記錄運動步數,積累氧氣值。還可偷

每日養生app2018-06-03

每日養生,天天健康

體育訓練成績評定2018-06-03

通用課目體育訓練成績評定