nginx 詳解 - 詳細配置說明
yum -y install gcc gcc-c++ autoconf pcre pcre-devel make automake yum -y install wget httpd-tools vim 複製程式碼
關閉 iptables
檢視iptables規則
iptables -L 或 iptables -t nat -L 複製程式碼
關閉 iptables 規則
iptables -F 或 iptables -t nat -F 複製程式碼
關閉 SELinux
檢視是否開啟
getenforce 複製程式碼
關閉
setenforce 0 複製程式碼
二、Nginx 簡介及安裝
Nginx 是一個開源且高效能、高可靠的 HTTP 中介軟體、代理服務。
安裝Nginx
開啟官網 ofollow,noindex">nginx.org/en/linux_pa…
To set up the yum repository for RHEL/CentOS, create the file named /etc/yum.repos.d/nginx.repo
with the following contents:
[nginx] name=nginx repo baseurl=http://nginx.org/packages/OS/OSRELEASE/$basearch/ gpgcheck=0 enabled=1 複製程式碼
Replace “ OS
” with “ rhel
” or “ centos
”, depending on the distribution used, and “ OSRELEASE
” with “ 6
” or “ 7
”, for 6.x or 7.x versions, respectively.
三、安裝目錄及配置講解
3.1 安裝目錄講解
檢視nginx的所有安裝目錄
rpm -ql nginx 複製程式碼
然後得到如下配置
[root@ ~]# rpm -ql nginx nginx日誌輪轉,用於logrotate服務的日誌切割 /etc/logrotate.d/nginx nginx主配置檔案 /etc/nginx/nginx.conf /etc/nginx /etc/nginx/conf.d /etc/nginx/conf.d/default.conf cgi配置相關,fastcgi配置 /etc/nginx/fastcgi_params /etc/nginx/scgi_params /etc/nginx/uwsgi_params 編碼轉換對映轉化檔案 /etc/nginx/koi-utf /etc/nginx/koi-win /etc/nginx/win-utf 設定http協議的 Content-Type 與副檔名對應關係 /etc/nginx/mime.types 用於配置出系統守護程序管理器管理方式 /etc/sysconfig/nginx /etc/sysconfig/nginx-debug /usr/lib/systemd/system/nginx-debug.service /usr/lib/systemd/system/nginx.service nginx模組目錄 /etc/nginx/modules /usr/lib64/nginx/modules /usr/lib64/nginx /usr/libexec/initscripts/legacy-actions/nginx /usr/libexec/initscripts/legacy-actions/nginx/check-reload /usr/libexec/initscripts/legacy-actions/nginx/upgrade nginx服務的啟動管理的終端命令 /usr/sbin/nginx /usr/sbin/nginx-debug nginx的手冊和幫助檔案 /usr/share/doc/nginx-1.14.0 /usr/share/doc/nginx-1.14.0/COPYRIGHT /usr/share/man/man8/nginx.8.gz /usr/share/nginx /usr/share/nginx/html /usr/share/nginx/html/50x.html /usr/share/nginx/html/index.html nginx 的快取目錄 /var/cache/nginx nginx日誌目錄 /var/log/nginx 複製程式碼
3.2 安裝編譯引數
命令 nginx -V
檢視所有編譯引數
3.3 Nginx 預設配置語法
引數 | 說明 |
---|---|
user | 設定nginx服務的系統使用使用者 |
worker_processes | 工作程序數(一般與伺服器核數保持一致) |
rror_log | nginx的錯誤日誌 |
pid | nginx服務啟動時候pid |
events -> worker_connections | 每個程序允許最大連線數 |
events -> use | 工作程序數 |
nginx 的預設配置檔案
檔案路徑 /etc/nginx/conf.d/default.conf
server { listen80; server_namelocalhost; #charset koi8-r; #access_log/var/log/nginx/host.access.logmain; location / { root/usr/share/nginx/html; indexindex.html index.htm; } #error_page404/404.html; # redirect server error pages to the static page /50x.html # error_page500 502 503 504/50x.html; location = /50x.html { root/usr/share/nginx/html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { #proxy_passhttp://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ \.php$ { #roothtml; #fastcgi_pass127.0.0.1:9000; #fastcgi_indexindex.php; #fastcgi_paramSCRIPT_FILENAME/scripts$fastcgi_script_name; #includefastcgi_params; #} # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { #denyall; #} } 複製程式碼
可以去 /usr/share/nginx/html/index.html
修改預設的展示頁面,也可以去 /usr/share/nginx/html/50x.html
修改錯誤頁面。
修改後重啟 nginx
systemctl reload nginx.service 或 systemctl restart nginx.service 複製程式碼
檢查 nginx 配置,結果出現 successful 表示成功
nginx -t -c /etc/nginx/nginx.conf 複製程式碼
重新載入配置
nginx -s reload -c /etc/nginx/nginx.conf 複製程式碼
四、常見 Nginx 中間架構
- 靜態資源WEB服務
- 代理服務
- 負載均衡排程器 SLB
- 動態快取
4.1 靜態資源WEB服務


配置語法-檔案讀取
Syntax: sendfile on|off; Default: sendfile off; Context: http,server,location,if in location 複製程式碼
引讀:--with-file-aio 非同步檔案讀取
配置語法- tcp_nopush
Syntax: tcp_nopush on|off; Default: tcp_nopush off; Context: http,server,location 複製程式碼
配置語法- tcp_nodelay
Syntax: tcp_nodelay on|off; Default: tcp_nodelay on; Context: http,server,location 複製程式碼
配置語法- 壓縮
Syntax: gzip_comp_level level; Default: gzip_comp_level 1; Context: http,server,location 複製程式碼
Syntax: gzip_http_version 1.0|1.1; Default: gzip_http_version 1.1; Context: http,server,location 複製程式碼
擴充套件 Nginx 壓縮模組
預讀 gzip 功能 http_gzip_static_module 應用支援 gunzip 的壓縮方式 http_gunzip_module 複製程式碼
瀏覽器快取設定
配置語法 - expires
新增 Cache-Control、Expires 頭
Syntax:expires [modified] time; expires epoch | max | off Default: expires off; Context: http, server, location, if in location 複製程式碼
跨域
*
表示允許所有的網站跨域,為了安全起見可以設定僅需要的網址
location ~ .*\.(htm|html)$ { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS; root /opt/app/code } 複製程式碼
基於 http_refer 防盜鏈配置模組
Syntax: valid_referers none | blocked | server_names | string...; Default: - Context: server, location, 複製程式碼
4.2 代理服務
-
正向代理代理的物件是客戶端
-
反向代理代理的物件是服務端
配置語法
Syntax: proxy_pass URL Default: - Context: location,if in location,limit_except 複製程式碼
URL 一般是以下三種
http://localhost:8080/uri/ https://192.168.1.1:8000/uri/ http://unix:/tmp/backend.socket:/uri/; 複製程式碼
4.3 負載均衡
HttpIndex模組
這個模組提供一個簡單方法來實現在輪詢和客戶端IP之間的後端伺服器負荷平衡。
配置範例:
resolver 10.0.0.1; upstream dynamic { zone upstream_dynamic 64k; hash $request_uri;#按照url的hash值來分配,同一個url分配到同一個伺服器 server backend1.example.comweight=5; server backend2.example.com:8080 fail_timeout=5s slow_start=30s; server 192.0.2.1max_fails=3; server backend3.example.comresolve; server backend4.example.comservice=http resolve; server backup1.example.com:8080backup; server backup2.example.com:8080backup; } server { location / { proxy_pass http://dynamic; health_check; } } 複製程式碼
狀態解釋
配置 | 說明 |
---|---|
down | 當前的server暫時不參與負載均衡 |
backup | 預留的備份伺服器 |
max_fails | 允許請求失敗的次數 |
fail_timeout | 經過max_fails 失敗後,服務暫停的時間 |
max_conns | 限制最大的接收的連線數 |
排程演算法
配置 | 說明 |
---|---|
輪詢 | 按時間順序逐一分配到不停的後端伺服器 |
加權輪詢 | weight值越大,分配到的訪問機率越高 |
ip_hash | 每個請求按照訪問IP的hash結果分配,這樣來自同一個ip固定訪問一個後端伺服器 |
url_hash | 按照訪問的URL的hash結果來分配請求,使每個URL定向到同一個後端伺服器 |
least_conn | 最少連線數,哪個機器連線數少就分發 |
hash關鍵數值 | hash自定義的key |
4.4 快取
快取型別分類:客戶端快取,代理快取,服務端快取
proxy_cache
Syntax:proxy_cache zone | off; Default: proxy_cache off; Context:http, server, location 複製程式碼
proxy_cache_path
Syntax: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]; Default:— Context:http 複製程式碼
例項
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=cache_zone:10m max_size=10g inactive=60m use_temp_path=off; map $request_method $purge_method { PURGE1; default 0; } server { ... location / { proxy_pass http://backend; proxy_cache cache_zone; proxy_cache_key $uri; proxy_cache_purge $purge_method; # 當分配的伺服器出現50X 錯誤時分配另一臺伺服器 proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504 } } 複製程式碼
五、Nginx深度學習
5.1 動靜分離
upstream java_api{ server 127.0.0.1:8080; } server { ... #匹配到jsp結尾的請求去請求伺服器 location ~ \.jsp$ { proxy_pass http://java_api; index index.html index.htm; } #匹配到圖片資源返回本地的內容 location ~ \.(jpg|png|gif)$ { expires 1h; gzip on; } } 複製程式碼
5.2 Nginx 的 rewrite規則
作用:實現 url 重寫以及重定向
使用場景:
語法
Syntax:rewrite regex replacement [flag]; Default:— Context:server, location, if 複製程式碼
If the specified regular expression matches a request URI, URI is changed as specified in the *replacement*
string. The rewrite
directives are executed sequentially in order of their appearance in the configuration file. It is possible to terminate further processing of the directives using flags. If a replacement string starts with “ http://
”, “ https://
”, or “ $scheme
”, the processing stops and the redirect is returned to a client.
An optional *flag*
parameter can be one of:
-
last
停止rewrite檢測
stops processing the current set of
ngx_http_rewrite_module
directives and starts a search for a new location matching the changed URI; -
break
停止rewrite檢測
stops processing the current set of
ngx_http_rewrite_module
directives as with thebreak directive; -
redirect
返回302臨時重定向,位址列會顯示跳轉後的地址
returns a temporary redirect with the 302 code; used if a replacement string does not start with “
http://
”, “https://
”, or “$scheme
”; -
permanent
返回302永久重定向,位址列會顯示跳轉後的地址
returns a permanent redirect with the 301 code.
The full redirect URL is formed according to the request scheme ( $scheme
) and the server_name_in_redirect andport_in_redirect directives.
Example:
server { ... rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 last; rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ralast; return403; ... } 複製程式碼
But if these directives are put inside the “ /download/
” location, the last
flag should be replaced by break
, or otherwise nginx will make 10 cycles and return the 500 error:
location /download/ { rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 break; rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.rabreak; return403; } 複製程式碼
If a *replacement*
string includes the new request arguments, the previous request arguments are appended after them. If this is undesired, putting a question mark at the end of a replacement string avoids having them appended, for example:
rewrite ^/users/(.*)$ /show?user=$1? last; 複製程式碼
If a regular expression includes the “ }
” or “ ;
” characters, the whole expressions should be enclosed in single or double quotes.
5.3 安全校驗 secure_link
指定並允許檢查請求的連結的真實性以及保護資源免遭未授權的訪問
限制連結生效週期
Syntax:secure_link expression; Default:— Context:http, server, location Syntax:secure_link_md5 expression; Default:— Context:http, server, location 複製程式碼
Example:
location /s/ { secure_link $arg_md5,$arg_expires; secure_link_md5 "$secure_link_expires$uri$remote_addr secret"; if ($secure_link = "") { return 403; } if ($secure_link = "0") { return 410; } ... } 複製程式碼
5.3 geoip_module 模組
基於 IP 地址匹配 MaxMind GeoIP 二進位制檔案,讀取 IP 所在地域資訊
安裝: yum install nginx-module-geoip
使用場景
- 區別國內外做HTTP 訪問規則
- 區別國內城市地域做 HTTP 訪問規則
5.4 配置 HTTPS
server { listen443 ssl; server_namewww.example.com; ssl_certificatewww.example.com.crt; ssl_certificate_key www.example.com.key; ssl_protocolsTLSv1 TLSv1.1 TLSv1.2; ssl_ciphersHIGH:!aNULL:!MD5; ... } 複製程式碼
HTTPS 服務優化
- 啟用 keepalive 長連線
- 設定 ssl session 快取
server{ listen 443; server_name116.62.103.228 jeson.t.imooc.io; keepalive_timeout100; ssl on; ssl_session_cacheshared:SSL:10m; ssl_session_timeout10m; ssl_certificatewww.example.com.crt; ssl_certificate_key www.example.com.key; index index.html index.htm; location / { root /opt/app/code; } } 複製程式碼
5.5 Nginx 與 Lua 開發
Lua 是一個簡潔、輕量、可擴充套件的指令碼語言
Nginx + Lua 優勢:充分的結合 Nginx 的併發處理 epoll 優勢和 Lua 的輕量實現簡單的功能且高併發的場景。
安裝
yum install lua 複製程式碼
執行 lua 有兩種方式:命令列和指令碼
-
命令列模式
在命令列輸入 lua 開啟命令列互動模式 複製程式碼
-
指令碼模式
編寫
test.lua
檔案,執行lua test.lua
執行
註釋
-- 行註釋 --[[ 塊註釋 --]] 複製程式碼
六、Nginx 常見問題
多個 server_name 的優先順序
如果多個檔案配置有相同的 server_name ,根據檔名先讀取到哪個檔案就載入哪個檔案的配置
location 匹配優先順序
=進行普通字元精確匹配,也就是完全匹配 ^~ 表示普通字元匹配,使用字首匹配 ~ \~*表示執行一個正則匹配() 複製程式碼
前兩種匹配到之後就不往下繼續匹配了,最後一種會繼續往下匹配,如果沒有匹配到,就用它的匹配。也就是前兩種優先順序比第三種高。
try_files 的使用
按順序檢查檔案是否存在
location / { try_files $uri $uri/ /index.php; } 複製程式碼
七、Nginx 效能優化
7.1 檔案控制代碼
檔案控制代碼:linux\Unix 一切皆檔案,檔案控制代碼就是一個索引
設定方式:系統全域性性修改,使用者區域性性修改,程序區域性性修改
修改方法:
系統全域性修改和針對使用者修改
vim /etc/security/limits.conf 複製程式碼
加入以下程式碼
# 給root使用者設定 root soft nofile 10000 root hard nofile 10000 # 給所有使用者全域性設定 *soft nofile 10000 *hard nofile 10000 複製程式碼
soft 不是強制性的,超過設定的值會提醒但不強制執行;hard 會強制執行
針對程序修改
vim /etc/nginx/nginx.conf 複製程式碼
新增以下程式碼
worker_rlimit_nofile 20000 複製程式碼
7.2 CPU 親和
檢視當前伺服器的 CPU 個數
cat /proc/cpuinfo | grep "physical id"|sort|uniq|wc -l 複製程式碼
檢視 CPU 核數
cat /proc/cpuinfo | grep "cpu cores"|uniq 複製程式碼
worker_processes = CPU 個數 * CPU 核數
假如有 2 個 CPU,每個 CPU 有 8 核,那 worker_processes
應該是16
開啟 nginx 配置檔案 vim /etc/nginx/nginx.conf
worker_processes16; worker_cpu_affinityauto; 複製程式碼
然後重新整理nginx配置 nginx -s reload -c /etc/nginx/nginx.conf
7.3 Nginx 的通用配置
usernginx; worker_processes1; worker_cpu_affinity auto; error_log/var/log/nginx/error.log warn; pid/var/run/nginx.pid; worker_rlimit_nofile 10000; events { use epoll; worker_connections1024; } http { include/etc/nginx/mime.types; default_typeapplication/octet-stream; charset utf-8; log_formatmain'$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.logmain; sendfileon; #tcp_nopushon; keepalive_timeout65; gzipon; gzip_disable"MSIE [1-6]\."; gzip_http_version 1.1; include /etc/nginx/conf.d/*.conf; } 複製程式碼
八、基於 Nginx 架構的安全
8.1 常見的惡意行為及防範手段
常見惡意行為:爬蟲行為和惡意抓取、資源盜用
常用防範手段:
基礎防盜鏈功能:目的不讓惡意使用者輕易爬取網站資料
secure_link_module: 提高資料安全性,對資料增加加密驗證和失效性,適合核心重要資料
access_module: 對後臺、部分使用者服務的資料提供 IP 防控
8.2 常見的攻擊手段
後臺密碼撞庫
通過猜測密碼欄位不斷對後臺系統登入性嘗試,獲取後臺登入密碼
防範手段:
- 後臺登入密碼複雜度
- access_module 對後臺提供 IP 防控
- 預警機制
檔案上傳漏洞
location ^~ /upload{ root /opt/app/images; if($requst_filename ~*(.*)\.php){ return 403; } } 複製程式碼
SQL 注入
利用未過濾/未稽核使用者輸入的攻擊方法,讓應用執行本不應該執行的 SQL 程式碼
Nginx + Lua 防火牆實現: github.com/loveshell/n…
以上就是 Nginx 學習筆記的全部內容。
作者正在組織寫一個有趣的開源專案 coderiver
,致力於打造全平臺型全棧精品開源專案。
coderiver
中文名 河碼,是一個為程式員和設計師提供專案協作的平臺。無論你是前端、後端、移動端開發人員,或是設計師、產品經理,都可以在平臺上釋出專案,與志同道合的小夥伴一起協作完成專案。
coderiver
河碼 類似程式設計師客棧,但主要目的是方便各細分領域人才之間技術交流,共同成長,多人協作完成專案。暫不涉及金錢交易。
計劃做成包含 pc端(Vue、React)、移動H5(Vue、React)、ReactNative混合開發、Android原生、微信小程式、Angular、Node、Flutter、java後端的全平臺型全棧專案,歡迎關注。
目前已經組建了幾十人的研發團隊,將致力於為大家提供最優質的開源專案。
專案地址: github.com/cachecats/c…
您的鼓勵是我前行最大的動力,歡迎點贊,歡迎送小星星:sparkles: ~