正文
一、安裝
1.1 yum安裝
(1) 配置好yum源與epel源
#本地光盤yum源 [development] name=dvdbase repo baseurl=file:///mnt/cdrom/ enabled=1 gpgcheck=1 gpgkey=file:///mnt/cdrom/RPM-GPG-KEY-CentOS-7 #在線阿里雲yum源 [aliyun] name=aliyun repo baseurl=https://mirrors.aliyun.com/centos/$releasever/os/$basearch/ enabled=1 gpgchedk=1 gpgkey=https://mirrors.aliyun.com/centos/$releasever/os/$basearch/RPM-GPG-KEY-CentOS-$releasever #在線阿里雲EPEL源 [aliyunEpel] name=aliyun epel baseurl=https://mirrors.aliyun.com/epel/$releasever/$basearch enabled=1 gpgcheck=1 gpgkey=https://mirrors.aliyun.com/epel/RPM-GPG-KEY-EPEL-$releasever
(2) 安裝
[root@localhost ~]# yum install -y nginx
1.2 編譯安裝
(1) 下載安裝包
[root@localhost ~]# wget https://nginx.org/download/nginx-1.18.0.tar.gz
(2) 安裝相關依賴包
[root@localhost ~]# yum install -y gcc pcre-devel openssl-devel zlib-devel
(3) 創建nginx用戶,解壓源碼包,開始編譯安裝
[root@localhost ~]# useradd -r -s /sbin/nologin nginx [root@localhost ~]# tar -xf nginx-1.18.0.tar.gz [root@localhost ~]# cd nginx-1.18.0/ [root@localhost nginx-1.18.0]# ./configure --prefix=/usr/local/nginx \ > --user=nginx \ > --group=nginx \ > --with-http_ssl_module \ > --with-http_v2_module \ > --with-http_realip_module \ > --with-http_stub_status_module \ > --with-http_gzip_static_module \ > --with-pcre \ > --with-stream \ > --with-stream_ssl_module \ > --with-stream_realip_module [root@localhost nginx-1.18.0]# make && make install

./configure --prefix=/usr/local/nginx \ --user=nginx \ --group=nginx \ --with-http_ssl_module \ --with-http_v2_module \ --with-http_realip_module \ --with-http_stub_status_module \ --with-http_gzip_static_module \ --with-pcre \ --with-stream \ --with-stream_ssl_module \ --with-stream_realip_module
(4) 啟動nginx
#直接啟動 [root@localhost ~]# /usr/local/nginx/sbin/nginx #或創建軟鏈接啟動 [root@localhost ~]# ln -s /usr/local/nginx/sbin/nginx /usr/sbin/ [root@localhost ~]# ll /usr/sbin/nginx lrwxrwxrwx 1 root root 27 Jun 17 11:42 /usr/sbin/nginx -> /usr/local/nginx/sbin/nginx [root@localhost ~]# nginx
二、配置文件詳解
#全局配置端 user nginx nginx; #啟動Ngnix工作進程的用戶和組 worker_processes [number | auto]; #啟動的工作進程數 worker_cpu_affinity 0001 0010 0100 1000 #將Nginx工作進程綁定到指定的CPU核心,默認Nginx是不進行進程綁定的 error_log file [debug | info | notice | warn | error | crit | alert | emerg] #錯誤日志配置 #error_log logs/error.log; #error_log logs/error.log notice; pid logs/nginx.pid; #pid文件保存路徑 work_priority 0; #工作進程的優先級 -20~19 work_rlimit_nofile 65536; #工作進程最大打開文件數 daemon off|on; #前台運行nginx用於測試,docker等環境,默認為on master_process off|on; #是否開啟Nginx的master-woker工作模式,關閉后 nginx就不會fork出worker子進程來處理請求,而是以master進程自身來處理請求 events { #events設置塊 worker_connections 1024; #設置單個nginx工作進程可以接愛的最大並發連接數據;
##在nginx作為http服務器的時候,最大連接數為worker_processes * worker_connctions;在nginx作為反向代理服務器的時候,最大連接數為worker_processes * worker_connections / 2 use epoll; #使用epoll事件驅動,Nginx支持眾多的事件驅動,比如select、poll、epoll,只能設置在events模塊中設置 accept_mutex on; #優化同一時刻只有一個請求而避免多個睡眠進程被喚醒的設置,on為防止被同時喚醒默認為off,全部喚醒的過程也成為"驚群",因此nginx剛安裝完以后要進行適當的優化 multi_accept on; #Nginx服務器的每個工作進程可以同時接受多個新的網絡連接,但是需要在配置文件中配置,此指令默認為關閉,即默認為一個工作進程只能一次接受一個新的網絡連接,打開后幾個同時接受多個 } http { #http設置塊 include mime.types; #導入支持的文件類型 default_type application/octet-stream; #設置默認的類型,會提示下載不匹配的類型文件 #日志配置部分 #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; #自定義優化參數 sendfile on; #指定是否使用sendfile系統調用來傳輸文件 #tcp_nopush on; #在開啟了sendfile的情況下,合並請求后統一發送給客戶端 #tcp_nodelay off; #在開啟了keepalived模式下的連接是否啟用TCP_NODELAY選項,當為off時,延遲0.2s發送,默認為on,不延遲發送,立即發送用戶相應報文 keepalive_timeout 65; #設置會話保持時間,單位是秒 #gzip on; #開啟文件壓縮 server { listen 80; #設置監聽地址和端口 server_name localhost; #設置server name,可以以空格隔開寫多個,支持正則表達式,如 *.aaa.com,www.aaa.* ~^www\d+\.aaa\.com$ default_server #charset koi8-r; #設置編碼格式,默認是俄語格式,可以改為utf-8 #access_log logs/host.access.log main; #設備訪問日志 location / { root html; #指定網站目錄 index index.html index.htm; #指定默認網頁文件,此指令由ngx_http_index_module模塊提供 } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { #以http的方式轉發php請求到指定web服務器 # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ \.php$ { #以fastcgi的方式轉發php請求到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; #} # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { #拒絕web形式訪問指定文件,如很多的網站都是通過.htaccess文件來改變自己的重定向等功能。 # deny all; #} } # another virtual host using mix of IP-, name-, and port-based configuration # #server { #自定義虛擬server # listen 8000; # listen somename:8080; # server_name somename alias another.alias; # location / { # root html; # index index.html index.htm; # } #} # HTTPS server # #server { #https服務器配置 # listen 443 ssl; # server_name localhost; # ssl_certificate cert.pem; # ssl_certificate_key cert.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; # } #} #include /usr/local/nginx/conf/conf.d/*.conf #導入其他路徑的配置文件 }
三、相關配置實例
3.1、站點基本配置
[root@localhost ~]# mkdir /usr/local/nginx/conf/conf.d [root@localhost ~]# vim /usr/local/nginx/conf/conf.d/aaa.conf server { listen 80; server_name www.aaa.com; location / { root html/aaa.com; index index.html index.htm } } [root@localhost ~]# mkdir /usr/local/nginx/html/aaa.com [root@localhost ~]# echo "www.aaa.com" > /usr/local/nginx/html/aaa.com/index.html [root@localhost ~]# nginx -s reload [root@localhost ~]# curl www.aaa.com www.aaa.com
3.2、root與alias
root:指定web的家目錄,在定義location的時候,文件的絕對路徑等於root+location,
alias:定義路徑別名,會把訪問的路徑重新定義到其指定的路徑
#root [root@localhost ~]# vim /usr/local/nginx/conf/conf.d/aaa.conf server { listen 80; server_name www.aaa.com; location / { root html/aaa.com; index index.html index.htm; } location /about { root html/aaa.com; #必須要在html/aaa.com目錄下創建一個about目錄才可以訪問,否則報錯 index index.html index.htm; } } [root@localhost ~]# mkdir /usr/local/nginx/html/aaa.com/about [root@localhost ~]# echo "about" > /usr/local/nginx/html/aaa.com/about/index.html [root@localhost ~]# tree /usr/local/nginx/html/aaa.com/ /usr/local/nginx/html/aaa.com/ ├── about │ └── index.html └── index.html [root@localhost ~]# nginx -s reload [root@localhost ~]# curl www.aaa.com/about/ about #alias [root@localhost ~]# vim /usr/local/nginx/conf/conf.d/aaa.conf server { listen 80; server_name www.aaa.com; location / { root html/aaa.com; index index.html index.htm; } location /about { #使用alias的時候uri后面如果加了斜杠則下面的路徑配置必須加斜杠,否則403 alias html/aaa.com; #當訪問about的時候,會顯示alias定義的html/aaa.com里面的內容 index index.html index.htm; } } [root@localhost ~]# nginx -s reload [root@localhost ~]# curl www.aaa.com/about/ www.aaa.com
3.3、location的匹配規則
語法規則: location [=|~|~*|^~] /uri/ { … } = #用於標准uri前,需要請求字串與uri精確匹配,如果匹配成功就停止 ~ #用於標准uri前,表示包含正則表達式並且區分大小寫 ~* #用於標准uri前,表示包含正則表達式並且不區分大寫 !~ #用於標准uri前,表示包含正則表達式並且區分大小寫不匹配 !~* #用於標准uri前,表示包含正則表達式並且不區分大小寫不匹配 ^~ #用於標准uri前,表示包含正則表達式並且匹配以什么開頭 $ #用於標准uri前,表示包含正則表達式並且匹配以什么結尾 \ #用於標准uri前,表示包含正則表達式並且轉義字符。可以轉. * ?等 * #用於標准uri前,表示包含正則表達式並且代表任意長度的任意字符
匹配優先級:=, ^~, ~/~*,/
location優先級:(location =) > (location 完整路徑) > (location ^~ 路徑) > (location ~,~* 正則順序) > (location 部分起始路徑) > (/)
location = /1.jpg { #只能訪問1.jpg root html/aaa.com/images; index index.html; } location ~ /A.?\.jpg { #只能訪問Ax.jpg,x表示任一單個字符 root html/aaa.com/images; index index.html; } location ~* /A.?\.jpg { #可以訪問Ax.jpg或Ax.JPG,x表示任一單個字符 root html/aaa.com/images; index index.html; } location ^~ /images { #匹配以images開頭 root html/aaa.com/images; index index.html; } location ~* \.(gif|jpg|jpeg|bmp|png|tiff|tif|ico|wmf|js)$ { #匹配結尾 root html/aaa.com/images; index index.html; }
3.4、Nginx 四層訪問控制
location /about { alias /data/nginx/html/pc; index index.html; deny 192.168.145.1; allow 192.168.145.0/24; allow 2001:0db8::/32; deny all; #先允許小部分,再拒絕大部分 }
3.5、Nginx賬戶認證功能
[root@localhost ~]# yum install -y httpd-tools [root@localhost ~]# htpasswd -cbm /usr/local/nginx/conf/.htpasswd user1 123456 Adding password for user user1 [root@localhost ~]# htpasswd -bm /usr/local/nginx/conf/.htpasswd user2 123456 Adding password for user user2 [root@localhost ~]# tail /usr/local/nginx/conf/.htpasswd user1:$apr1$jsO6E/ci$xvL4zCDCnH28SXoY00MjQ0 user2:$apr1$k00UYYEp$UKi8pQKdfPtQQplgLsxyF/ [root@localhost ~]# vim /usr/local/nginx/conf/conf.d/aaa.conf server { listen 80; server_name www.aaa.com; location / { root html/aaa.com; index index.html index.htm; } location /about { root html/aaa.com; index index.html index.htm; auth_basic "login password"; auth_basic_user_file /usr/local/nginx/conf/.htpasswd; } }
3.6、自定義錯誤頁面
[root@localhost ~]# cat /usr/local/nginx/html/error.html Sorry,This is a error page. [root@localhost ~]# vim /usr/local/nginx/conf/conf.d/aaa.conf server { listen 80; server_name www.aaa.com; error_page 500 502 503 504 404 /error.html location / { root html/aaa.com; index index.html index.htm; } location /error.html { root html; } }
3.7、自定義訪問日志
[root@localhost ~]# vim /usr/local/nginx/conf/conf.d/aaa.conf server { listen 80; server_name www.aaa.com; error_page 500 502 503 504 404 /error.html; access_log logs/www.aaa.com_access.log; error_log logs/www.aaa.com_error.log; location / { root html/aaa.com; index index.html index.htm; } location = /error.html { root html; } }
3.8、檢測文件是否存在
try_files會按順序檢查文件是否存在,返回第一個找到的文件或文件夾(結尾加斜線表示為文件夾),如果所有文件或文件夾都找不到,會進行一個內部重定向到最后一個參數。只有最后一個參數可以引起一個內部重定向,之前的參數只設置內部URI的指向。最后一個參數是回退URI且必須存在,否則會出現內部500錯誤。
location /about { root html/aaa.com; index index.html index.htm; #try_files $uri $uri/index.html $uri.html /about/default.html; try_files $uri $uri/index.html $uri.html =489; } #當訪問到不存在的uri會顯示default.html,如果是自定義的狀態碼則會顯示在返回數據的狀態碼中,如 [root@localhost ~]# curl www.aaa.com/about/xx.html default page [root@localhost ~]# curl --head www.aaa.com/about/xx.html HTTP/1.1 489 Server: nginx/1.18.0 Date: Wed, 17 Jun 2020 09:49:00 GMT Content-Length: 0 Connection: keep-alive
3.9、長連接配置
keepalive_timeout number; #設定保持連接超時時長,0表示禁止長連接,默認為75s,通常配置在http字段作為站點全局配置
keepalive_requests number; #在一次長連接上所允許請求的資源的最大數量,默認為100次
keepalive_requests 3; keepalive_timeout 60 60; #開啟長連接后,返回客戶端的會話保持時間為60s,單次長連接累計請求達到指定次數請求或65秒就會被斷開,后面的60為發送給客戶端應答報文頭部中顯示的超時時間設置為60s:如不設置客戶端將不顯示超時時間。 Keep-Alive:timeout=60 #瀏覽器收到的服務器返回的報文 #如果設置為0表示關閉會話保持功能,將如下顯示: Connection:close #瀏覽器收到的服務器返回的報文
3.10、作為下載服務器配置
[root@localhost ~]# vim /usr/local/nginx/conf/conf.d/aaa.conf server { listen 80; server_name www.aaa.com; location / { root html/aaa.com; index index.html index.htm; } location /download { root html/aaa.com; autoindex on; autoindex_exact_size on; autoindex_localtime on; } } [root@localhost ~]# mkdir /usr/local/nginx/html/aaa.com/download [root@localhost ~]# cp nginx-1.18.0.tar.gz /usr/local/nginx/html/aaa.com/download/
#瀏覽器訪問 www.aaa.com/download 測試
3.11、作為上傳服務器
client_max_body_size 1m; #設置允許客戶端上傳單個文件的最大值,默認值為1m client_body_buffer_size size; #用於接收每個客戶端請求報文的body部分的緩沖區大小;默認16k;超出此大小時,其將被暫存到磁盤上的由下面client_body_temp_path指令所定義的位置 client_body_temp_path path [level1 [level2 [level3]]]; #設定存儲客戶端請求報文的body部分的臨時存儲路徑及子目錄結構和數量,目錄名為16進制的數字,使用hash之后的值從后往前截取1位、2位、2位作為文件名
配置示例: client_max_body_size 10m; client_body_buffer_size 16k; client_body_temp_path /usr/local/nginx/temp 1 2 2; #reload Nginx會自動創建temp目錄
3.12、隱藏Nginx Server版本信息
server_tokens off; #隱藏Nginx server版本
3.13、其它配置項
keepalive_disable none | browser ...; #對哪種瀏覽器禁用長連接 limit_except method ... { ... } #僅用於location限制客戶端使用除了指定的請求方法之外的其它方法 method:GET, HEAD, POST, PUT, DELETE,MKCOL, COPY, MOVE, OPTIONS, PROPFIND,ROPPATCH, LOCK, UNLOCK, PATCH limit_except GET { allow 192.168.0.0/24; allow 192.168.7.101; deny all; }
aio on | off #是否啟用asynchronous file I/O(AIO)功能,需要編譯開啟 linux 2.6以上內核提供以下幾個系統調用來支持aio: 1、SYS_io_setup:建立aio 的context 2、SYS_io_submit: 提交I/O操作請求 3、SYS_io_getevents:獲取已完成的I/O事件 4、SYS_io_cancel:取消I/O操作請求 5、SYS_io_destroy:毀銷aio的context directio size | off; #操作完全和aio相反,aio是讀取文件而directio是寫文件到磁盤,啟用直接I/O,默認為關閉,當文件大於等於給定大小時,例如directio 4m,同步(直接)寫磁盤,而非寫緩存。
open_file_cache off; #是否緩存打開過的文件信息 open_file_cache max=N [inactive=time]; nginx可以緩存以下三種信息: (1) 文件元數據:文件的描述符、文件大小和最近一次的修改時間 (2) 打開的目錄結構 (3) 沒有找到的或者沒有權限訪問的文件的相關信息 max=N:可緩存的緩存項上限數量;達到上限后會使用LRU(Least recently used,最近最少使用)算法實現管理 inactive=time:緩存項的非活動時長,在此處指定的時長內未被命中的或命中的次數少於open_file_cache_min_uses指令所指定的次數的緩存項即為非活動項,將被刪除 open_file_cache_min_uses number; #open_file_cache指令的inactive參數指定的時長內,至少被命中此處指定的次數方可被歸類為活動項,默認值為1 open_file_cache_errors on | off; #是否緩存查找時發生錯誤的文件一類的信息,默認值為off open_file_cache_valid time; #緩存項有效性的檢查驗證頻率,默認值為60s #配置實例: open_file_cache max=10000 inactive=60s; #最大緩存10000個文件,非活動數據超時時長60s open_file_cache_valid 60s; #每間隔60s檢查一下緩存數據有效性 open_file_cache_min_uses 5; #60秒內至少被命中訪問5次才被標記為活動數據 open_file_cache_errors on; #緩存錯誤信息
四、高級應用
4.1、狀態頁配置
基於nginx模塊ngx_http_auth_basic_module實現,在編譯安裝nginx的時候需要添加編譯參數--with-http_stub_status_module,否則配置完成之后監測會是提示語法錯誤。
location /nginx_status { stub_status; allow 192.168.145.0/24; allow 127.0.0.1; deny all; } [root@www ~]# curl 192.168.145.27/nginx_status/ Active connections: 4 server accepts handled requests 13 13 28 Reading: 0 Writing: 1 Waiting: 3 Active connections: 當前處於活動狀態的客戶端連接數,包括連接等待空閑連接數。 accepts: 統計總值,Nginx自啟動后已經接受的客戶端請求的總數。 handled: 統計總值,Nginx自啟動后已經處理完成的客戶端請求的總數,通常等於accepts,除非有因worker_connections限制等被拒絕的連接。 requests: 統計總值,Nginx自啟動后客戶端發來的總的請求數。 Reading: 當前狀態,正在讀取客戶端請求報文首部的連接的連接數。 Writing: 當前狀態,正在向客戶端發送響應報文過程中的連接數。 Waiting: 當前狀態,正在等待客戶端發出請求的空閑連接數,開啟 keep-alive的情況下,這個值等於active – (reading+writing)
4.2、變量使用
Nginx的變量可以在配置文件中引用,作為功能判斷或者日志等場景使用,變量可以分為內置變量和自定義變量,內置變量是由nginx模塊自帶,通過變量可以獲取到眾多的與客戶端訪問相關的值。
(1) 內置變量
$remote_addr; #存放了客戶端的地址,注意是客戶端的公網IP,也就是一家人訪問一個網站,則會顯示為路由器的公網IP $args; #變量中存放了URL中的指令,例如http://www.aaa.com/about/index.do?id=202006&partner=search中的id=202006&partner=search $document_root; #保存了針對當前資源的請求的系統根目錄,如/usr/local/nginx/html $document_uri; #保存了當前請求中不包含指令的URI,注意是不包含請求的指令,例如http://www.aaa.com/about/index.do?id=202006&partner=search中的/about/index.do $host; #存放了請求的host名稱。 $http_user_agent; #客戶端瀏覽器的詳細信息 $http_cookie; #客戶端的cookie信息。 limit_rate 10240; echo $limit_rate; #如果nginx服務器使用limit_rate配置了顯示網絡速率,則會顯示,如果沒有設置, 則顯示0。 $remote_port; #客戶端請求Nginx服務器時隨機打開的端口,這是每個客戶端自己的端口。 $remote_user; #已經經過Auth Basic Module驗證的用戶名。 $request_body_file; #做反向代理時發給后端服務器的本地資源的名稱。 $request_method; #請求資源的方式,GET/PUT/DELETE等 $request_filename; #當前請求的資源文件的路徑名稱,由root或alias指令與URI請求生成的文件絕對路徑,如/apps/nginx/html/main/index.html $request_uri; #包含請求參數的原始URI,不包含主機名,如:/main/index.do?id=20190221&partner=search 。 $scheme; #請求的協議,如ftp,https,http等。 $server_protocol; #保存了客戶端請求資源使用的協議的版本,如HTTP/1.0,HTTP/1.1,HTTP/2.0等。 $server_addr; #保存了服務器的IP地址。 $server_name; #請求的服務器的主機名。
(2) 自定義變量
假如需要自定義變量名稱和值,使用指令set $variable value;,則方法如下:
Syntax: set $variable value;
Default: —
Context: server, location, if
set $name aaa; echo $name; set $my_port $server_port; echo $my_port; echo "$server_name:$server_port";
4.3、壓縮功能
Nginx支持對指定類型的文件進行壓縮然后再傳輸給客戶端,而且壓縮還可以設置壓縮比例,壓縮后的文件大小將比源文件顯著變小,這樣有助於降低出口帶寬的利用率,降低企業的IT支出,不過會占用相應的CPU資源。Nginx對文件的壓縮功能是依賴於模塊ngx_http_gzip_module。
#相關配置參數: gzip on | off; #啟用或禁用gzip壓縮,默認關閉 gzip_comp_level level; #壓縮比由低到高從1到9,默認為1 gzip_disable "MSIE [1-6]\."; #禁用IE6 gzip功能 gzip_min_length 1k; #gzip壓縮的最小文件,小於設置值的文件將不會壓縮 gzip_http_version 1.0 | 1.1; #啟用壓縮功能時,協議的最小版本,默認HTTP/1.1 gzip_buffers number size; #指定Nginx服務需要向服務器申請的緩存空間的個數*大小,默認32 4k|16 8k; gzip_types mime-type ...; #指明僅對哪些類型的資源執行壓縮操作;默認為gzip_types text/html,不用顯示指定,否則出錯 gzip_vary on | off; #如果啟用壓縮,是否在響應報文首部插入"Vary: Accept-Encoding" 如: gzip on; gzip_comp_level 5; gzip_min_length 1k; gzip_types text/plain application/javascript application/x-javascripttext/css application/xml text/javascript application/x-httpd-php image/jpegimage/gif image/png; gzip_vary on
4.4、https配置
Nginx 的https功能基於模塊ngx_http_ssl_module實現,因此如果是編譯安裝的nginx要使用參數ngx_http_ssl_module開啟ssl功能,但是作為nginx的核心功能,yum安裝的nginx默認就是開啟的,編譯安裝的nginx需要指定編譯參數--with-http_ssl_module開啟。
ssl on | off; #為指定的虛擬主機配置是否啟用ssl功能,此功能在1.15.0廢棄,使用listen [ssl]替代。 ssl_certificate /path/to/file; #當前虛擬主機使用使用的公鑰文件,一般是crt文件 ssl_certificate_key /path/to/file; #當前虛擬主機使用的私鑰文件,一般是key文件 ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2]; #支持ssl協議版本,早期為ssl現在是TSL,默認為后三個 ssl_session_cache off | none | [builtin[:size]] [shared:name:size]; #配置ssl緩存 off: 關閉緩存 none: 通知客戶端支持ssl session cache,但實際不支持 builtin[:size]:使用OpenSSL內建緩存,為每worker進程私有 [shared:name:size]:在各worker之間使用一個共享的緩存,需要定義一個緩存名稱和緩存空間大小,一兆可以存儲4000個會話信息,多個虛擬主機可以使用相同的緩存名稱。 ssl_session_timeout time;#客戶端連接可以復用ssl session cache中緩存的有效時長,默認5m
#nginx證書配置
listen 80;
listen 443 ssl;
ssl_certificate /usr/local/nginx/certs/www.aaa.com.crt;
ssl_certificate_key /usr/local/nginx/certs/www.aaa.com.key;
ssl_session_cache shared:sslcache:20m;
ssl_session_timeout 10m;
實現過程:
#自簽名CA證書 [root@www ~]# cd /usr/local/nginx/ [root@www nginx]# mkdir certs [root@www nginx]# cd certs/ [root@www certs]# openssl req -newkey rsa:4096 -nodes -sha256 -keyout ca.key -x509 -days 365 -out ca.crt Generating a 4096 bit RSA private key ..............................................................................................................................................................................................................++ .............................................................................................................++ writing new private key to 'ca.key' ----- 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) []:GD #省份 Locality Name (eg, city) [Default City]:SZ #城市 Organization Name (eg, company) [Default Company Ltd]:tech.Ltd #公司名稱 Organizational Unit Name (eg, section) []:ops #部門 Common Name (eg, your name or your server's hostname) []:aaa.com #通用名稱 Email Address []:43112211@qq.com #郵箱 [root@www certs]# ll total 8 -rw-r--r-- 1 root root 2065 Jun 18 15:46 ca.crt -rw-r--r-- 1 root root 3272 Jun 18 15:46 ca.key #自制key和csr文件 [root@www certs]# openssl req -newkey rsa:4096 -nodes -sha256 -keyout www.aaa.com.key -out www.aaa.com.csr Generating a 4096 bit RSA private key ..............................................++ ..++ writing new private key to 'www.aaa.com.key' ----- 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) []:GD Locality Name (eg, city) [Default City]:SZ Organization Name (eg, company) [Default Company Ltd]:tech.Ltd Organizational Unit Name (eg, section) []:ops Common Name (eg, your name or your server's hostname) []:www.aaa.com Email Address []:43112211@qq.com Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []: An optional company name []: [root@www certs]# ll total 16 -rw-r--r-- 1 root root 2065 Jun 18 15:46 ca.crt -rw-r--r-- 1 root root 3272 Jun 18 15:46 ca.key -rw-r--r-- 1 root root 1728 Jun 18 15:49 www.aaa.com.csr -rw-r--r-- 1 root root 3268 Jun 18 15:49 www.aaa.com.key #簽發證書 [root@www certs]# openssl x509 -req -days 365 -in www.aaa.com.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out www.aaa.com.crt Signature ok subject=/C=CN/ST=GD/L=SZ/O=tech.Ltd/OU=ops/CN=www.aaa.com/emailAddress=43112211@qq.com Getting CA Private Key #查看證書內容 [root@www certs]# openssl x509 -in www.aaa.com.crt -noout -text Certificate: Data: Version: 1 (0x0) Serial Number: c4:6b:f1:61:33:25:43:9b Signature Algorithm: sha256WithRSAEncryption Issuer: C=CN, ST=GD, L=SZ, O=tech.Ltd, OU=ops, CN=aaa.com/emailAddress=43112211@qq.com Validity Not Before: Jun 18 07:50:31 2020 GMT Not After : Jun 18 07:50:31 2021 GMT Subject: C=CN, ST=GD, L=SZ, O=tech.Ltd, OU=ops, CN=www.aaa.com/emailAddress=43112211@qq.com Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (4096 bit) .....
4.5、關於favicon.ico
favicon.ico 文件是瀏覽器收藏網址時顯示的圖標,當客戶端使用瀏覽器問頁面時,瀏覽器會自己主動發起請求獲取頁面的favicon.ico文件,但是當瀏覽器請求的favicon.ico文件不存在時,服務器會記錄404日志,而且瀏覽器也會顯示404報錯。
#解決辦法: #1.服務器不記錄訪問日志: location = /favicon.ico { log_not_found off; access_log off; } #2.將圖標保存到指定目錄訪問: #location ~ ^/favicon\.ico$ { location = /favicon.ico { root /data/nginx/html/pc/images; }
4.6、rewrite指令
通過正則表達式的匹配來改變URI,可以同時存在一個或多個指令,按照順序依次對URI進行匹配,rewrite主要是針對用戶請求的URL或者是URI做具體處理。
用法:rewrite regex replacement [flag];
(1) rewrite flag
利用nginx的rewrite的指令,可以實現url的重新跳轉,rewrtie有四種不同的flag,分別是redirect(臨時重定向)、permanent(永久重定向)、break和last。其中前兩種是跳轉型的flag,后兩種是代理型,跳轉型是指有客戶端瀏覽器重新對新地址進行請求,代理型是在WEB服務器內部實現跳轉的。
redirect; #臨時重定向,重寫完成后以臨時重定向方式直接返回重寫后生成的新URL給客戶端,由客戶端重新發起請求;使用相對路徑,或者http://或https://開頭,狀態碼:302 permanent; #重寫完成后以永久重定向方式直接返回重寫后生成的新URL給客戶端,由客戶端重新發起請求,狀態碼:301 last; #重寫完成后停止對當前URI在當前location中后續的其它重寫操作,而后對新的URL啟動新一輪重寫檢查,不建議在location中使用 break; #重寫完成后停止對當前URL在當前location中后續的其它重寫操作,而后直接跳轉至重寫規則配置塊之后的其它配置;結束循環,建議在location中使用
(2) 臨時重定向與永久重定向
location / { root /usr/local/nginx/html/pc; index index.html; rewrite / http://www.aaa.com permanent; #rewrite / http://www.aaa.com redirect; }
(3) last與break
location /break { rewrite ^/break/(.*) /test$1 break; #break不會跳轉到其他的location return 666 "break"; } location /last { rewrite ^/last/(.*) /test$1 last; #last會跳轉到其他的location繼續匹配新的URI return 888 "last"; } location /test { return 999 "test"; }
(4) 自動跳轉https
server { listen 80; listen 443 ssl; ssl_certificate /usr/local/nginx/certs/www.aaa.com.crt; ssl_certificate_key /usr/local/nginx/certs/www.aaa.com.key; ssl_session_cache shared:sslcache:20m; ssl_session_timeout 10m; server_name www.aaa.com; location / { root html/aaa.com; index index.html index.htm; if ($scheme = http){ #不加條件判斷,會導致死循環 rewrite / https://www.aaa.com permanent; } } } #還一種是對監聽的80端口進行跳轉 server { listen 80 default_server; server_name www.aaa.com; rewrite ^(.*)$ https://$server_name$1 permanent; }
(5) 判斷文件是否存在
例:當用戶訪問到公司網站的時輸入了一個錯誤的URL,可以將用戶重定向至官網首頁 location / { root /usr/local/nginx/html/pc; index index.html; if (!-f $request_filename) { #return 404 "No Page"; rewrite (.*) http://www.aaa.net/index.html; } }
(6) 防盜鏈
防盜鏈基於客戶端攜帶的referer實現,referer是記錄打開一個頁面之前記錄是從哪個頁面跳轉過來的標記信息,如果別人只鏈接了自己網站圖片或某個單獨的資源,而不是打開了網站的整個頁面,這就是盜鏈,referer就是之前的那個網站域名,正常的referer信息有以下幾種:
none: #請求報文首部沒有referer首部,比如用戶直接在瀏覽器輸入域名訪問web網站,就沒有referer信息。 blocked: #請求報文有referer首部,但無有效值,比如為空。 server_names: #referer首部中包含本主機名及即nginx 監聽的server_name。 arbitrary_string: #自定義指定字符串,可使用*作通配符。 regular expression: #被指定的正則表達式模式匹配到的字符串,要使用~開頭,例如:~.*\.aaa\.com
location ^~ /images { root /usr/local/nginx/pc; index index.html; valid_referers none blocked server_names *.aaa.com www.aaa.* api.online.test/v1/hostlist ~\.google\. ~\.baidu\.; #定義有效的referer if ($invalid_referer) { #假如是使用其他的無效的referer訪問: return 403; #返回狀態碼403 } }
4.7、代理功能
ngx_http_proxy_module: 將客戶端的請求以http協議轉發至指定服務器進行處理。
ngx_stream_proxy_module: 將客戶端的請求以tcp協議轉發至指定服務器處理。
ngx_http_fastcgi_module: 將客戶端對php的請求以fastcgi協議轉發至指定服務器助理。
ngx_http_uwsgi_module: 將客戶端對Python的請求以uwsgi協議轉發至指定服務器處理。
配置參數:
proxy_pass; #用來設置將客戶端請求轉發給的后端服務器的主機,可以是主機名、IP地址:端口的方式,也可以代理到預先設置的主機群組;
location /web { index index.html; proxy_pass http://192.168.7.103:80; #不帶斜線將訪問的/web,等於訪問后端服務器 http://192.168.7.103:80/web/index.html,即后端服務器配置的站點根目錄要有web目錄才可以被訪問,這是一個追加/web到后端服務器 http://servername:port/WEB/INDEX.HTML的操作 proxy_pass http://192.168.7.103:80/; #帶斜線,等於訪問后端服務器的http://192.168.7.103:80/index.html 內容返回給客戶端 }
(1) 正向代理配置
#代理服務器上配置 http { resolver 8.8.8.8; server { listen 8088; location / { proxy_pass http://$http_host$request_uri; } } } #客戶端配置 export "http_proxy=http://[user]:[pass]@host:port/" 如:export http_proxy=http://192.168.145.27:8088
(2) 反向代理配置
server { listen 80; server_name www.magedu.net; location / { proxy_pass http://192.168.145.7:80/; } } #也可以對指定location進行代理 location /web { proxy_pass http://192.168.7.103:80/; #注意有后面的/ }
(3) 代理緩存功能
#代理緩存功能默認關閉,可通過下面參數配置: proxy_cache zone | off; #指明調用的緩存,或關閉緩存機制;默認off;Context:http, server, location proxy_cache_key string; #緩存中用於"鍵"的內容,默認值:proxy_cache_key $scheme$proxy_host$request_uri;
proxy_cache_valid [code ...] time; #定義對特定響應碼的響應內容的緩存時長,定義在http{...}中
示例: proxy_cache_valid 200 302 10m; proxy_cache_valid 404 1m; proxy_cache_path; #定義可用於proxy功能的緩存;Context:http proxy_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] [loader_files=number] [loader_sleep=time] [loader_threshold=time]
[purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time]; 例:在http配置定義緩存信息 proxy_cache_path /var/cache/nginx/proxy_cache #定義緩存保存路徑,proxy_cache會自動創建 levels=1:2:2 #定義緩存目錄結構層次,1:2:2可以生成2^4x2^8x2^8=1048576個目錄 keys_zone=proxycache:20m #指內存中緩存的大小,主要用於存放key和metadata(如:使用次數) inactive=120s #緩存有效時間 max_size=1g; #最大磁盤占用空間,磁盤存入文件內容的緩存空間最大值
#調用緩存功能,需要定義在相應的配置段,如server{...};或者location等 proxy_cache proxycache; proxy_cache_key $request_uri; proxy_cache_valid 200 302 301 1h; proxy_cache_valid any 1m; proxy_cache_use_stale; #在被代理的后端服務器出現哪種情況下,可直接使用過期的緩存響應客戶端 proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_502 | http_503 | http_504 | http_403 | http_404 | off ; #默認是off proxy_cache_methods GET | HEAD | POST ...; #對哪些客戶端請求方法對應的響應進行緩存,GET和HEAD方法總是被緩存 proxy_set_header field value; #設定發往后端主機的請求報文的請求首部的值 Context: http, server, location proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 請求報文的標准格式如下: X-Forwarded-For: client1, proxy1, proxy2 [root@www ~]# vim /usr/local/nginx/conf/nginx.conf #配置在nginx.conf http配置段 proxy_cache_path /usr/local/nginx/proxycache levels=1:1:1 keys_zone=proxycache:20m inactive=120s max_size=1g; [root@www ~]# vim /usr/local/nginx/conf/conf.d/pc.conf #要緩存的URL 或者放在server配置項對所有URL都進行緩存 location /web { proxy_pass http://192.168.27.7:80/; proxy_set_header clientip $remote_addr; proxy_cache proxycache; proxy_cache_key $request_uri; proxy_cache_valid 200 302 301 1h; proxy_cache_valid any 1m; }
(4) 添加頭部報文信息
Syntax: add_header name value [always];
Default: —
Context: http, server, location, if in location
#添加自定義首部 add_header name value [always]; add_header X-Via $server_addr; add_header X-Cache $upstream_cache_status; add_header X-Accel $server_name; #添加自定義響應信息的尾部, 1.13.2版后支持 add_trailer name value [always]; #nginx配置: location /web { proxy_pass http://192.168.27.7:80/; proxy_set_header clientip $remote_addr; proxy_cache proxycache; proxy_cache_key $request_uri; proxy_cache_valid 200 302 301 1h; proxy_cache_valid any 1m; add_header X-Via $server_addr; add_header X-Cache $upstream_cache_status; add_header X-Accel $server_name; }
4.8、負載均衡
(1) http的負載均衡-upstream
配置參數: upstream name { #自定義一組服務器,配置在http內 server address [parameters]; #配置一個后端web服務器,配置在upstream內,至少要有一個server服務器配置。 }
#server支持的parameters如下: weight=number #設置權重,默認為1 max_conns=number #給當前server設置最大活動鏈接數,默認為0表示沒有限制 max_fails=number #對后端服務器連續監測失敗多少次就標記為不可用 fail_timeout=time #對后端服務器的單次監測超時時間,默認為10秒 backup #設置為備份服務器,當所有服務器不可用時將重新啟用次服務器 down #標記為down狀態 resolve #當server定義的是主機名的時候,當A記錄發生變化會自動應用新IP而不用重啟Nginx hash KEY consistent; #基於指定key做hash計算,使用consistent參數,將使用ketama一致性hash算法,適用於后端是Cache服務器(如varnish)時使用,consistent定義使用一致性hash運算,一致性hash基於取模運算。所謂取模運算,就是計算兩個數相除之后的余數,比如10%7=3, 7%4=3 hash $request_uri consistent; #基於用戶請求的uri做hash ip_hash; #源地址hash調度方法,基於的客戶端的remote_addr(源地址)做hash計算,以實現會話保持
調度算法: rr: 輪詢,默認的調度方式,將所有請求都按照時間順序分配到不同的服務上; weight: 權重,指定每個服務的權重比例,weight和訪問比率成正比; ip_hash: 指定負載均衡器按照基於客戶端IP的分配方式,這個方法確保了相同的客戶端的請求一直發送到相同的服務器,以保證session會話。這樣每個訪客都固定訪問一個后端服務器,可以解決session不能跨服務器的問題; least_conn: 把請求轉發給連接數較少的后端服務器。輪詢算法是把請求平均的轉發給各個后端,使它們的負載大致相同;但是,有些請求占用的時間很長,會導致其所在的后端負載較高。這種情況下,least_conn這種方式就可以達到更好的負載均衡效果 fair: 按照服務器端的響應時間來分配請求,響應時間短的優先分配; url_hash: 按訪問url的hash結果來分配請求,使每個url定向到同一個后端服務器,要配合緩存命中來使用。同一個資源多次請求,可能會到達不同的服務器上,導致不必要的多次下載,緩存命中率不高,以及一些資源時間的浪費;
而使用url_hash,可以使得同一個url(也就是同一個資源請求)會到達同一台服務器,一旦緩存住了資源,再此收到請求,就可以從緩存中讀取; 例: upstream webserver { #hash $request_uri consistent; #ip_hash; #least_conn; server 192.168.27.7:80 weight=1 fail_timeout=5s max_fails=3; #后端服務器狀態監測 server 192.168.27.17:80 weight=1 fail_timeout=5s max_fails=3 backup; } server { listen 80; server_name www.aaa.net; location / { index index.html index.php; root /usr/local/nginx/html/pc; } location /web { index index.html; proxy_pass http://webserver/; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #客戶端IP透傳,添加客戶端IP到報文頭部 } }
(2) tcp的負載均衡
Nginx在1.9.0版本開始支持tcp模式的負載均衡,在1.9.13版本開始支持udp協議的負載,udp主要用於DNS的域名解析,其配置方式和指令和http代理類似,其基於ngx_stream_proxy_module模塊實現tcp負載,另外基於模塊ngx_stream_upstream_module實現后端。
配置參數: stream { #定義stream upstream backend { #定義后端服務器 hash $remote_addr consistent; #定義調度算法 server backend1.example.com:12345 weight=5; #定義具體server server 127.0.0.1:12345 max_fails=3 fail_timeout=30s; server unix:/tmp/backend3; } upstream dns { #定義后端服務器 server 192.168.0.1:53535; #定義具體server server dns.example.com:53; } server { #定義server listen 12345; #監聽IP:PORT proxy_connect_timeout 1s; #連接超時時間 proxy_timeout 3s; #轉發超時時間 proxy_pass backend; #轉發到具體服務器組 } server { listen 127.0.0.1:53 udp reuseport; proxy_timeout 20s; proxy_pass dns; } server { listen [::1]:12345; proxy_pass unix:/tmp/stream.socket; } }
實例1:Redis負載均衡 stream { upstream redis_server { #hash $remote_addr consistent; server 192.168.145.27:6379 max_fails=3 fail_timeout=30s; } server { listen 192.168.145.7:6379; proxy_connect_timeout 3s; proxy_timeout 3s; proxy_pass redis_server; } } 實例2:mysql負載均衡 stream { upstream mysql_server { least_conn; server 192.168.145.27:3306 max_fails=3 fail_timeout=30s; } server { listen 192.168.145.7:3306; proxy_connect_timeout 6s; proxy_timeout 15s; proxy_pass mysql_server; } }
4.9、FastCGI配置
Nginx基於模塊ngx_http_fastcgi_module實現通過fastcgi協議將指定的客戶端請求轉發至php-fpm處理,其配置參數如下:
fastcgi_pass address; #轉發請求到后端服務器,address為后端的fastcgi server的地址,可用位置:location, if in location fastcgi_index name; #fastcgi默認的主頁資源,示例:fastcgi_index index.php; fastcgi_param parameter value [if_not_empty]; #設置傳遞給FastCGI服務器的參數值,可以是文本,變量或組合,可用於將Nginx的內置變量賦值給自定義key fastcgi_param REMOTE_ADDR $remote_addr; #客戶端源IP fastcgi_param REMOTE_PORT $remote_port; #客戶端源端口 fastcgi_param SERVER_ADDR $server_addr; #請求的服務器IP地址 fastcgi_param SERVER_PORT $server_port; #請求的服務器端口 fastcgi_param SERVER_NAME $server_name; #請求的server name
Nginx默認配置示例: location ~ \.php$ { root html; #$document_root 調用root目錄 fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; #默認腳本路徑 #fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; #或用$document_root, include fastcgi_params; }
fastcgi緩存定義: fastcgi_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time]
[loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time]; path #緩存位置為磁盤上的文件系統路徑 max_size=size #磁盤path路徑中用於緩存數據的緩存空間上限 levels=levels: #緩存目錄的層級數量,以及每一級的目錄數量,levels=ONE:TWO:THREE,示例:leves=1:2:2 keys_zone=name:size #設置緩存名稱及k/v映射的內存空間的名稱及大小 inactive=time #緩存有效時間,默認10分鍾,需要在指定時間滿足fastcgi_cache_min_uses 次數被視為活動緩存 fastcgi緩存調用: fastcgi_cache zone | off; #調用指定的緩存空間來緩存數據,可用位置:http, server, location fastcgi_cache_key string; #定義用作緩存項的key的字符串,示例:fastcgi_cache_key $request_uri; fastcgi_cache_methods GET | HEAD | POST ...; #為哪些請求方法使用緩存 fastcgi_cache_min_uses number; #緩存空間中的緩存項在inactive定義的非活動時間內至少要被訪問到此處所指定的次數方可被認作活動項 fastcgi_keep_conn on | off; #收到后端服務器響應后,fastcgi服務器是否關閉連接,建議啟用長連接 fastcgi_cache_valid [code ...] time; #不同的響應碼各自的緩存時長 fastcgi_hide_header field; #隱藏響應頭指定信息 fastcgi_pass_header field; #返回響應頭指定信息,默認不會將Status、X-Accel-...返回
Nginx與php-fpm實現:
(1) 安裝php-fpm [root@www ~]# yum install php-fpm php-mysql -y [root@www ~]# systemctl start php-fpm (2) 准備php測試頁 [root@www ~]# vim /usr/local/nginx/html/aaa.com/index.php <?php phpinfo(); ?> (3) nginx配置轉發 [root@www ~]# vim /usr/local/nginx/conf/conf.d/aaa.conf server { listen 80; server_name www.aaa.com; location / { root html/aaa.com; index index.html index.htm; } location ~ \.php$ { root html/aaa.com; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } } (3) 重啟nginx並使用瀏覽器測試 [root@www ~]# nginx -s reload php相關配置優化: [root@www ~]# grep "^[a-Z]" /etc/php-fpm.conf include=/etc/php-fpm.d/*.conf pid = /run/php-fpm/php-fpm.pid error_log = /var/log/php-fpm/error.log daemonize = yes #是否后台啟動 [root@www ~]# grep "^[a-Z]" /etc/php-fpm.d/www.conf listen = 127.0.0.1:9000 #監聽地址及IP listen.allowed_clients = 127.0.0.1 #允許客戶端從哪個源IP地址訪問,要允許所有則在行首加 ; 注釋即可 user = nginx #php-fpm啟動的用戶和組,會涉及到后期文件的權限問題 group = nginx pm = dynamic #動態模式進程管理 pm.max_children = 500 #靜態方式下開啟的php-fpm進程數量,在動態方式下他限定php-fpm的最大進程數 pm.start_servers = 100 #動態模式下初始進程數,必須大於等於pm.min_spare_servers和小於等於pm.max_children的值 pm.min_spare_servers = 100 #最小空閑進程數 pm.max_spare_servers = 200 #最大空閑進程數 pm.max_requests = 500000 #進程累計請求回收值,會重啟 pm.status_path = /pm_status #狀態訪問URL ping.path = /ping #ping訪問動地址 ping.response = ping-pong #ping返回值 slowlog = /var/log/php-fpm/www-slow.log #慢日志路徑 php_admin_value[error_log] = /var/log/php-fpm/www-error.log #錯誤日志 php_admin_flag[log_errors] = on php_value[session.save_handler] = files #phpsession保存方式及路徑 php_value[session.save_path] = /var/lib/php/session #當時使用file保存session的文件路徑
五、系統參數優化
默認的Linux內核參數考慮的是最通用場景,不符合用於支持高並發訪問的Web服務器的定義,根據業務特點來進行調整,當Nginx作為靜態web內容服務器、反向代理或者提供壓縮服務器的服務器時,內核參數的調整都是不同的,此處針對最通用的、使Nginx支持更多並發請求的TCP網絡參數做簡單的配置,修改/etc/sysctl.conf來更改內核參數。
fs.file-max = 1000000 #表示單個進程較大可以打開的句柄數 net.ipv4.tcp_tw_reuse = 1 #參數設置為 1 ,表示允許將TIME_WAIT狀態的socket重新用於新的TCP鏈接,這對於服務器來說意義重大,因為總有大量TIME_WAIT狀態的鏈接存在 net.ipv4.tcp_keepalive_time = 600 #當keepalive啟動時,TCP發送keepalive消息的頻度;默認是2小時,將其設置為10分鍾,可更快的清理無效鏈接 net.ipv4.tcp_fin_timeout = 30 #當服務器主動關閉鏈接時,socket保持在FIN_WAIT_2狀態的較大時間 net.ipv4.tcp_max_tw_buckets = 5000 #表示操作系統允許TIME_WAIT套接字數量的較大值,如超過此值,TIME_WAIT套接字將立刻被清除並打印警告信息,默認為8000,過多的TIME_WAIT套接字會使Web服務器變慢 net.ipv4.ip_local_port_range = 1024 65000 #定義UDP和TCP鏈接的本地端口的取值范圍 net.ipv4.tcp_rmem = 10240 87380 12582912 #定義了TCP接受緩存的最小值、默認值、較大值 net.ipv4.tcp_wmem = 10240 87380 12582912 #定義TCP發送緩存的最小值、默認值、較大值 net.core.netdev_max_backlog = 8096 #當網卡接收數據包的速度大於內核處理速度時,會有一個列隊保存這些數據包。這個參數表示該列隊的較大值 net.core.rmem_default = 6291456 #表示內核套接字接受緩存區默認大小 net.core.wmem_default = 6291456 #表示內核套接字發送緩存區默認大小 net.core.rmem_max = 12582912 #表示內核套接字接受緩存區較大大小 net.core.wmem_max = 12582912 #表示內核套接字發送緩存區較大大小 注意:以上的四個參數,需要根據業務邏輯和實際的硬件成本來綜合考慮 net.ipv4.tcp_syncookies = 1 #與性能無關。用於解決TCP的SYN攻擊 net.ipv4.tcp_max_syn_backlog = 8192 #這個參數表示TCP三次握手建立階段接受SYN請求列隊的較大長度,默認1024,將其設置的大一些可使出現Nginx繁忙來不及accept新連接時,Linux不至於丟失客戶端發起的鏈接請求 net.ipv4.tcp_tw_recycle = 1 #這個參數用於設置啟用timewait快速回收 net.core.somaxconn=262114 #選項默認值是128,這個參數用於調節系統同時發起的TCP連接數,在高並發的請求中,默認的值可能會導致鏈接超時或者重傳,因此需要結合高並發請求數來調節此值。 net.ipv4.tcp_max_orphans=262114 #選項用於設定系統中最多有多少個TCP套接字不被關聯到任何一個用戶文件句柄上。如果超過這個數字,孤立鏈接將立即被復位並輸出警告信息。這個限制指示為了防止簡單的DOS攻擊,不用過分依靠這個限制甚至認為的減小這個值,更多的情況是增加這個值