1. 程式人生 > >Nginx之常用基本配置(一)

Nginx之常用基本配置(一)

  上一篇部落格我們大概介紹了一下nginx,nginx的架構,nginx編譯安裝和nginx命令的用法,回顧請參考https://www.cnblogs.com/qiuhom-1874/p/12366808.html;今天我們來配置簡單的配置下nginx和一些簡單指令說明。

  nginx和httpd類似都是高度模組化的軟體,不同的模組有著不同的功能,想要把nginx配置好,首先我們需要了解各個模組的用法以及模組選項的用法和說明。首先我們來了解下nginx用yum安裝後,程式環境

[root@www ~]# rpm -ql nginx
/etc/logrotate.d/nginx
/etc/nginx/fastcgi.conf
/etc/nginx/fastcgi.conf.default
/etc/nginx/fastcgi_params
/etc/nginx/fastcgi_params.default
/etc/nginx/koi-utf
/etc/nginx/koi-win
/etc/nginx/mime.types
/etc/nginx/mime.types.default
/etc/nginx/nginx.conf
/etc/nginx/nginx.conf.default
/etc/nginx/scgi_params
/etc/nginx/scgi_params.default
/etc/nginx/uwsgi_params
/etc/nginx/uwsgi_params.default
/etc/nginx/win-utf
/usr/bin/nginx-upgrade
/usr/lib/systemd/system/nginx.service
/usr/lib64/nginx/modules
/usr/sbin/nginx
/usr/share/doc/nginx-1.16.1
……省略部分內容
/var/lib/nginx
/var/lib/nginx/tmp
/var/log/nginx
[root@www ~]# 

  提示:從上面的顯示,我們大概可以瞭解到nginx的主配置檔案是/etc/ngxin/ngxin.conf,nginx.conf.default是預設配置檔案,從這個檔案中我們可以瞭解到nginx的預設配置是怎麼配置的;主程式是/usr/sbin/nginx,日誌檔案路徑是/var/log/nginx,Unit File是nginx.service;/etc/nginx/fastcgi.conf和fastcgi_parems,這兩個檔案一個是fastcig協議的配置檔案,一個是變數配置檔案。瞭解了nginx 的程式環境,我們在來看看主配置檔案內容

[root@www ~]# cat /etc/nginx/nginx.conf
# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    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  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl http2 default_server;
#        listen       [::]:443 ssl http2 default_server;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers HIGH:!aNULL:!MD5;
#        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        location / {
#        }
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }

}

[root@www ~]# 

  提示:主配置檔案結構大致可以分為main段(全域性配置段)和http配置段或者mail配置段或者stream段,後面的http配置段或mail配置段或stream配置段,主要看nginx用於什麼功能,如果單純的用於web伺服器,那麼後面的mail和stream配置段就可以不要了,也就是說有關web的配置我們必須要在http配置段配置;同樣的如果nginx用於郵件代理我們就需要把有關郵件代理的配置放到mail配置段,如果用於四層負載均衡,我們需要把對應的配置寫到stream配置段;我們先說一下全域性配置段吧

  user指令:表示指定執行worker程序的使用者

[root@www ~]# head /etc/nginx/nginx.conf
  For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
[root@www ~]# ps aux |grep nginx
root       1425  0.0  0.0 120832  2244 ?        Ss   19:49   0:00 nginx: master process nginx
nginx      1426  0.0  0.0 121228  3132 ?        S    19:49   0:00 nginx: worker process
nginx      1427  0.0  0.0 121228  3132 ?        S    19:49   0:00 nginx: worker process
nginx      1428  0.0  0.0 121228  3132 ?        S    19:49   0:00 nginx: worker process
nginx      1429  0.0  0.0 121228  3132 ?        S    19:49   0:00 nginx: worker process
root       1439  0.0  0.0 112660   968 pts/0    S+   19:51   0:00 grep --color=auto nginx
[root@www ~]#

  提示:通常情況都不建議nginx用root執行;如果是叢集環境建議統一程序執行使用者,其次必須統一時間

  worker_processes :指定worker程序的數量,一般是和執行nginx主機的CUP核心數來定,一般都是小於或者等於物理cpu核心數,auto表示自動去匹配cup核心數來啟動worker程序數量

[root@www ~]# lscpu 
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                4
On-line CPU(s) list:   0-3
Thread(s) per core:    1
Core(s) per socket:    2
Socket(s):             2
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 158
Model name:            Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz
Stepping:              9
CPU MHz:               3599.644
CPU max MHz:           0.0000
CPU min MHz:           0.0000
BogoMIPS:              7200.06
Hypervisor vendor:     VMware
Virtualization type:   full
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              8192K
NUMA node0 CPU(s):     0-3
Flags:                 fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts nopl xtopology tsc_reliable nonstop_tsc aperfmperf eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 invpcid rtm rdseed adx smap xsaveopt xsavec xgetbv1 dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp
[root@www ~]# ps aux |grep nginx
root       1425  0.0  0.1 121500  5272 ?        Ss   19:49   0:00 nginx: master process nginx
nginx      1453  0.0  0.0 121748  3668 ?        S    19:56   0:00 nginx: worker process
nginx      1454  0.0  0.0 121748  3668 ?        S    19:56   0:00 nginx: worker process
nginx      1455  0.0  0.0 121748  3668 ?        S    19:56   0:00 nginx: worker process
nginx      1456  0.0  0.0 121748  3668 ?        S    19:56   0:00 nginx: worker process
root       1465  0.0  0.0 112660   972 pts/0    S+   19:57   0:00 grep --color=auto nginx
[root@www ~]# 

  error_log表示指定nginx錯誤日誌存放檔案

[root@www ~]# ll /var/log/nginx/error.log 
-rw-r--r-- 1 root root 120 Feb 27 19:56 /var/log/nginx/error.log
[root@www ~]# cat /var/log/nginx/error.log
2020/02/27 19:52:18 [notice] 1442#0: signal process started
2020/02/27 19:56:47 [notice] 1452#0: signal process started
[root@www ~]# 

  pid表示指定pid檔案

[root@www ~]# ps aux |grep nginx
root       1567  0.0  0.0 120832  2248 ?        Ss   20:05   0:00 nginx: master process /usr/sbin/nginx
nginx      1568  0.0  0.0 121228  3336 ?        S    20:05   0:00 nginx: worker process
nginx      1569  0.0  0.0 121228  3336 ?        S    20:05   0:00 nginx: worker process
nginx      1570  0.0  0.0 121228  3336 ?        S    20:05   0:00 nginx: worker process
nginx      1571  0.0  0.0 121228  3136 ?        S    20:05   0:00 nginx: worker process
root       1574  0.0  0.0 112660   972 pts/0    S+   20:05   0:00 grep --color=auto nginx
[root@www ~]# ll /var/run/nginx.pid 
-rw-r--r-- 1 root root 5 Feb 27 20:05 /var/run/nginx.pid
[root@www ~]# nginx -s stop
[root@www ~]# ll /var/run/nginx.pid 
ls: cannot access /var/run/nginx.pid: No such file or directory
[root@www ~]# 

  提示:pid檔案就是存放nginx主控程序的程序號的,如果nginx沒有執行或者停止了服務,那麼pid檔案也會跟著消失;這裡提示一下在centos7上/var/run 和/run是同一資料夾 ,它倆做的是硬連結

[root@www ~]# ll -id /var/run/
1150 drwxr-xr-x 22 root root 620 Feb 27 20:07 /var/run/
[root@www ~]# ll -id /run
1150 drwxr-xr-x 22 root root 620 Feb 27 20:07 /run
[root@www ~]# 

  提示:兩個資料夾的inode號都是同一個

  include此指令表示把某些地方的配置匯入到此地;這個指定配置的時候需要注意放的位置;正因為有了這個功能,我們就可以把很多不同功能的配置用專有的檔案來配置,這樣既方便管理,也很容易讀;

  events此配置段表示配置有關事件驅動相關的配置

  worker_connections :每個worker程序所能夠開啟的最大併發連線數;

  use method:指定併發請求的處理方法;如use epoll;

  accept_mutex on|off:處理新的連線請求的方法;on表示各worker程序輪流處理新請求,off表示每來一個新請求就會通知所有的worker程序

  有關效能優化的全域性配置

  worker_cpu_affinity cpumask:手動或自動繫結cpu,預設情況下是沒有繫結cpu的,這意味著worker程序會在每個CPU上來會排程的,這樣一來在cpu就存在頻繁的切換,影響效能;我們可以手動把每個程序繫結到不同的CPU上。禁止worker程序在每個CPU上來回切換

 

  提示:在沒有繫結cpu時,我們對nginx worker程序發起併發連線請求,可以看到4個worker程序在不同的CUP上來回切換,很顯然這無疑在給系統多餘的開銷,我們可以繫結nginx 的worker執行緒。

[root@www ~]# grep worker_cpu /etc/nginx/nginx.conf
worker_cpu_affinity 0001 0010 0100 1000;
[root@www ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@www ~]# nginx -s reload
[root@www ~]# 

  提示:如果你有的CPU是八核的,那麼就需要用8個0來表示,其中第一個程序對應最右側的0,如果需要繫結到該cpu核心上,則對應位為1即可;

  提示:繫結cpu我們也可以直接使用worker_cpu_affinity auto;來指定,讓其自動繫結到每個cpu核心上去

   worker_priority number:指定worker程序的nice值,設定worker程序優先順序;[-20,19]

[root@www ~]# grep "worker_priority" /etc/nginx/nginx.conf
worker_priority -5;
[root@www ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@www ~]# nginx -s reload                             
[root@www ~]# ps axo comm,pid,nice,psr|grep nginx
nginx             2583   0   0
nginx            31567  -5   0
nginx            31568  -5   1
nginx            31569  -5   2
nginx            31570  -5   3
[root@www ~]# 

  以上就是常用的全域性配置段指令的說明和使用,詳細請參考nginx官方文件http://nginx.org/en/docs/ngx_core_module.html

  http協議的相關配置

  在主配置檔案中我們可以看到有一個以http開頭的配置段,這個配置段主要配置nginx工作成web服務的配置

  server:這個指令表示定義個虛擬主機類似httpd裡的virtualhost,這也是一個http裡的一個子配置段,裡面有server_name指令 root等等

    server_name:表示指定虛擬主機名稱;指明虛擬主機的主機名稱;後可跟多個由空白字元分隔的字串;支援*通配任意長度的任意字元;支援~起始的字元做正則表示式模式匹配;

      匹配機制:首先是字串精確匹配;其次是左側*萬用字元,然後右側*萬用字元,最後是正則表示式

    root:設定web資源路徑對映;用於指明使用者請求的url所對應的本地檔案系統上的文件所在目錄路徑;可用的位置:http, server, location, if in location;

    listen:指定虛擬主機監聽的地址和埠,如果只指定埠未指定地址,表示監聽伺服器上的所有地址,如果在server裡沒有指定埠,對應的虛擬主機將監聽在預設埠80上

      listen address[:port] [default_server] [ssl] [http2 | spdy]  [backlog=number] [rcvbuf=size] [sndbuf=size]

        default_server:設定為預設虛擬主機;

        ssl:限制僅能通過ssl連線該服務

        backlog=number:指定後援佇列長度

        sndbuf=size:指定傳送緩衝區大小

 

   提示:我們這樣配置後,在hosts檔案中新增對應的解析後,用瀏覽器訪問www.ilinux.io,此時它就會把預設主機裡的對映路徑下的資源響應我們

[root@www ~]# echo "this is default path " > /usr/share/nginx/html/test.html
[root@www ~]# cat /usr/share/nginx/html/test.html
this is default path 
[root@www ~]# curl http://www.ilinux.io/test.html
this is default path 
[root@www ~]# 

    tcp_nodelay on|off :在keepalived模式下的連線是否啟用TCP_NODELAY選項;

    tcp_nopush on|off:在sendfile模式下,是否啟用TCP_CORK選項;

    sendfile on|off:是否啟用sendfile功能;

  通常情況下以上三項都是開啟的,TCP_NODELAY主要是傳送報文延時問題,如果開啟了該功能選項,表示不管資料包多小都及時傳送,如果關閉了,通常會等到一定量的資料報文一起傳送,對於小報文延時就很高,TCP_CORK主要是解決小包問題,它和TCP_NODELAY相反,啟用表示要到一定量的資料包後才傳送,關閉表示不用等一定量的資料報文再發送,它們兩者都是解決小包問題,前者應用在長連線模式下,後者應用在sendfile模式下;sendfile模式解決了核心到使用者應用程式,使用者應用程式到核心的重複過程,它可將資料報文直接從核心載入到網絡卡socket快取區,直接傳送出去;這三項都和效能相關,通常都是開啟的;

  location:此指令用於實現從uri到檔案系統的路徑對映;ngnix會根據使用者請求的URI來檢查定義的所有location,並找出一個最佳匹配,而後應用其配置;在一個server中location配置段可存在多個;

    語法:location [ = | ~ | ~* | ^~ ] uri { ... }

      =:對URI做精確匹配;

      ^~:對URI的左半部分做匹配檢查,不區分字元大小寫;

      ~:對URI做正則表示式模式匹配,區分字元大小寫;

      ~*:對URI做正則表示式模式匹配,不區分字元大小寫;

      不帶符號:匹配起始於此uri的所有的url;

      匹配優先順序:=, ^~, ~/~*,不帶符號;

   示例:

location = / {
    [ configuration A ]
}

location / {
    [ configuration B ]
}

location /documents/ {
    [ configuration C ]
}

location ^~ /images/ {
    [ configuration D ]
}

location ~* \.(gif|jpg|jpeg)$ {
    [ configuration E ]
}

  說明:如果是使用者請求uri是/ 那麼在以上location中將匹配到A,如果是/index 將匹配到B,如果是/documents/index將匹配到C,如果是/images/1.jpg將匹配到D和E,但是D的優先順序高於E,所有應用D的配置,如果是/document/1.jpg將匹配到C和E,但是E的優先順序高於C,所以會應用E的配置;

  alias path:定義資源路徑別名,僅用於location中;它和root定義資源路徑不同的是,root定義的資源路徑應用在/uri/左側的'/',而alias定義的資源路徑應用在/uri/的右側'/';

  示例:

[root@www ~]# cat /etc/nginx/conf.d/test.conf
server {

        listen 80;
        server_name www.ilinux.io;

        location  /test/ {
                root /data/web/html/;

                allow all;
        }
}
[root@www ~]# cat /data/web/html/index.html 
this is /data/web/html/index.html
[root@www ~]# cat /data/web/html/index.html 
this is /data/web/html/index.html
[root@www ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@www ~]# nginx -s reload
[root@www ~]# curl http://www.ilinux.io/test/index.html
this is /data/web/html/test/index.html
[root@www ~]# 

  提示:我們用root來指定資源路徑時,我們訪問/test/.index.html 它返回的是/data/web/html/test/index.html,就相當於把location左側的“/”更換成root定義的路徑,使用者訪問資源的真實路徑就是/data/web/html/test/index.html;換句話講,root指定資源路徑,匹配使用者URI最左側“/”,真實路徑是root指定的路徑+使用者URI(不帶左側"/")

[root@www ~]# cat /etc/nginx/conf.d/test.conf 
server {

        listen 80;
        server_name www.ilinux.io;

        location  /test/ {
                alias /data/web/html/;

                allow all;
        }
}
[root@www ~]# cat /data/web/html/index.html 
this is /data/web/html/index.html
[root@www ~]# cat /data/web/html/test/index.html 
this is /data/web/html/test/index.html
[root@www ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@www ~]# nginx -s reload
[root@www ~]# curl http://www.ilinux.io/test/index.html
this is /data/web/html/index.html
[root@www ~]# 

  提示:用alias 指定資源路徑時,我們訪問/test/index.html,它返回/data/web/html/index.html,相當於alias 指定的資源路徑覆蓋了使用者請求的URI最右側的“/”,換句話說使用者URI最右側的“/”就是alias所指定的資源路徑,使用者訪問/test/index.html 就相當於訪問/data/web/html/index.html;這裡還需要注意一點的是 alias 指定資源路徑時,必須是“/”結尾,如果不以“/”結尾,資源將無法找到;對於root來講是不是“/”結尾這個無要求;

  index file:指定預設主頁,可配置在http, server, location;

  示例:

[root@www html]# cat /etc/nginx/conf.d/test.conf 
server {

        listen 80;
        server_name www.ilinux.io;
        location  /test/ {
                alias /data/web/html/;
                index test.html;
                allow all;
        }
}
[root@www html]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@www html]# nginx -s reload
[root@www html]# curl http://www.ilinux.io/test/
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>
[root@www html]# echo "this is default page" > /data/web/html/test.html
[root@www html]# curl http://www.ilinux.io/test/                       
this is default page
[root@www html]# 

  error_page code ... [=[response]] uri:指定錯誤頁面,匹配指定的狀態碼,返回指定的URL

  示例:

[root@www html]# cat /etc/nginx/conf.d/test.conf
server {

        listen 80;
        server_name www.ilinux.io;
        location  /test/ {
                alias /data/web/html/;
                index test.html;
                allow all;
        }
        error_page 404 403 /error.html;

        location /error.html {
                root /data/web/html/error;
        }
}
[root@www html]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@www html]# nginx -s reload
[root@www html]# mkdir /data/web/html/error/
[root@www html]# echo "error page" > /data/web/html/error/error.html
[root@www html]# curl http://www.ilinux.io/abc/
error page
[root@www html]# 

  提示:通過指定錯誤頁面,我們可以自定義錯誤頁面,也可以對錯誤頁面用專有的location來做配