一、概述
Nginx是一款輕量級的Web 服務器/反向代理服務器及電子郵件(IMAP/POP3)代理服務器,並在一個BSD-like 協議下發行。其特點是佔有內存少,併發能力強,事實上Nginx的併發能力確實在同類型的網頁服務器中表現較好,中國使用Nginx網站用戶有:百度、京東、新浪、網易、騰訊、淘寶等。Nginx採用C進行編寫,能夠支持高達 50,000 個併發連接數的響應,使用了epoll and kqueue作爲開發模型。Nginx 啓動特別容易,並且幾乎可以做到7*24不間斷運行,即使運行數個月也不需要重新啓動。它還能夠不間斷服務的情況下進行軟件版本的升級。官網地址:http://nginx.org/en/
二、安裝部署
這裏以在centos6.5上安裝爲例,環境準備:
gcc:安裝nginx需要先將官網下載的源碼進行編譯,編譯依賴gcc環境,如果沒有gcc環境,需要安裝gcc,yum install gcc-c++。
PCRE:是一個perl庫,包括perl兼容的正則表達式庫。Nginx的http模塊使用pcre來解析正則表達式,所以需要在linux下安裝pcere庫,yum install -y pcre pcre-devel(pcre-devel是使用了pcre開發的一個二次開發庫,nginx也需要此庫)。
Zlib:提供了很多壓縮和解壓縮的方式,Nginx使用zlib對http包的內容進行gzip,yum install -y zlib zlib-devel.
Openssl:是一個強大的安全套接字層密碼庫,囊括了主要的密碼算法、常用的密鑰和證書封裝管理及SSL協議,並提供豐富的應用程序測試或其他目的使用。Nginx不僅支持http協議,還支持https協議,yum install -y openssl openssl-devel。
下載安裝包:wget http://nginx.org/download/nginx-1.8.0.tar.gz
解壓、配置、編譯:
tar zxvf nginx-1.8.0.tar.gz
cd nginx-1.8.0
./configure --prefix=/usr/local/nginx
make && make install
進入 /usr/local/nginx, 看到如下4個目錄
./
....conf 配置文件
... html 網頁文件
...logs 日誌文件
...sbin 主要二進制程序
啓動:[root@localhost nginx]# ./sbin/nginx
停止:
[root@localhost nginx]# ./sbin/nginx -s stop --快速停止(先查出nginx的進程id再使用kill強制殺掉,不推薦使用)
[root@localhost nginx]# ./sbin/nginx -s quit --平滑停止(待nginx進程處理任務完畢進行停止,推薦使用)
重啓(修改配置文件生效)
[root@localhost nginx]# ./sbin/nginx reload
運行後查看nginx進程可以發現它有一個主進程和多個工作進程。其中,工作進程是單線程的,且不需要特殊授權即可運行。
Nginx的信號控制
Kill -信號選項 nginx的主進程號
Kill -HUP 4873
Kill -信號控制 `cat /xxx/path/log/nginx.pid`
Kil; -USR1 `cat /xxx/path/log/nginx.pid`
TERM, INT |
Quick shutdown |
QUIT |
Graceful shutdown 優雅的關閉進程,即等請求結束後再關閉 |
HUP |
Configuration reload ,Start the new worker processes with a new configuration Gracefully shutdown the old worker processes 改變配置文件,平滑的重讀配置文件 |
USR1 |
Reopen the log files 重讀日誌,在日誌按月/日分割時有用 |
USR2 |
Upgrade Executable on the fly 平滑的升級 |
WINCH |
Gracefully shutdown the worker processes 優雅關閉舊的進程(配合USR2來進行升級) |
|
|
三、配置詳解
配置文件名爲nginx.conf,放置在如/usr/local/nginx/conf目錄下,基本內容框架如下:
// 全局區
worker_processes 1; // 有1個工作的子進程,可以自行修改,但太大無益,因爲要爭奪CPU,一般設置爲 CPU數*核數
Event {
// 一般是配置nginx連接的特性,如1個work能同時允許多少連接
worker_connections 1024; // 這是指 一個子進程最大允許連1024個連接
}
http { //這是配置http服務器的主要段
server { // 這是虛擬主機段
location { //定位,把特殊的路徑或文件再次定位 ,如image目錄單獨處理
}
}
server {
}
}
1)虛擬主機配置
例子1: 基於域名的虛擬主機
server {
listen 80; #監聽端口
server_name a.com; #監聽域名
location / {
root /var/www/a.com; #根目錄定位
index index.html;
}
}
例子2: 基於端口的虛擬主機配置
server {
listen 8080;
server_name 192.168.1.204;
location / {
root /var/www/html8080;
index index.html;
access_log logs/proxy.access.log main;
}
2)日誌管理
在server段中,我們可以看到類似信息,如: access_log logs/proxy.access.log main;
這說明該server, 它的訪問日誌的文件是logs/proxy.access.log,使用的格式”main”格式。除了main格式,你可以自定義其他格式。
i、默認的日誌格式: main
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
表示:遠程IP - 遠程用戶/用戶時間 請求方法(如GET/POST) 請求體body長度 referer來源信息
http-user-agent用戶代理/蜘蛛 ,被轉發的請求的原始IP
其中,http_x_forwarded_for在經過代理時,代理把你的本來IP加在此頭信息中,傳輸你的原始IP
ii、自定義日誌格式:聲明一個獨特的log_format並命名
log_format mylog '$remote_addr- "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
在下面的server/location,我們就可以引用 mylog
Nginx允許針對不同的server做不同的Log ,在server段中,這樣來聲明
access_log logs/access_8080.log mylog;
聲明log log位置 log格式;
實際應用: shell+定時任務+nginx信號管理,完成日誌按日期存儲
分析思路: 凌晨00:00:01,把昨天的日誌重命名,放在相應的目錄下,再USR1信息號控制nginx重新生成新的日誌文件
具體腳本:
#!/bin/bash
base_path='/usr/local/nginx/logs'
log_path=$(date -d yesterday +"%Y%m")
day=$(date -d yesterday +"%d")
mkdir -p $base_path/$log_path
mv $base_path/access.log $base_path/$log_path/access_$day.log
#echo $base_path/$log_path/access_$day.log
kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`
定時任務
Crontab 編輯定時任務
01 00 * * * /xxx/path/b.sh 每天0時1分(建議在02-04點之間,系統負載小)
3)壓縮管理
zip on|off
gzip_buffers 4K|8K 緩衝(和硬盤塊相當)
gzip_comp_level [1-9] 推薦6
gzip_disable 正則匹配UA
gzip_min_length 200
gzip_http_version 1.0|1.1
gzip_proxied
gzip_types text/plain,application/xml
gzip_vary on|off
參數解析可以參考:https://www.cnblogs.com/yingsong/p/6047311.html
4)支持瀏覽器緩存
location ~ .*\.(jpg|png|gif|bmp)$ {
expires 30d;
}
5)location和rewrite規則
location規則:
=開頭表示精確匹配;
^~ 開頭表示uri以某個常規字符串開頭,不是正則匹配;
~ 開頭表示區分大小寫的正則匹配;
~* 開頭表示不區分大小寫的正則匹配
/ 通用匹配, 如果沒有其它匹配,任何請求都會匹配到
順序 no優先級:
(location =) > (location 完整路徑) > (location ^~ 路徑) > (location ~,~* 正則順序) > (location 部分起始路徑) > (/)
rewrite常用的命令
if (條件) {} 設定條件,再進行重寫
set #設置變量
return #返回狀態碼
break #跳出rewrite
rewrite #重寫
根據方法重寫:
if ($request_method = GET) {
return 405;
}
根據瀏覽器判斷重寫:
if ($http_user_agent ~ MSIE) {
#return 404;
rewrite ^(.*)$ /ie.html break;
}
參考資料:https://segmentfault.com/a/1190000002797606
6)反向代理
location ~ .*\.(jpg|png|gif|bmp)$ {
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://192.168.1.204:8080;
}
7)負載均衡
upstream image_pool {
server 192.168.1.204:8080 weight=1 max_fails=2 fail_timeout=30s;
server 192.168.1.204:8081 weight=1 max_fails=2 fail_timeout=30s;
}
負載均衡還可以引入第三方插件,涉及到很多調度算法,可以參考:https://www.cnblogs.com/1214804270hacker/p/9325150.html
8)性能優化
i、連接memcached
location / {
set $memcached_key "$uri?$args"; #memcache的鍵
memcached_pass 127.0.0.1:11211;
error_page 404 = /writemem.php; 回調
index index.php index.html index.htm;
}
多臺memcached的話,先用upstream模塊,把多臺memcached服務器寫成一組,並起組名,然後memcached_pass爲組名
ii、Nginx參數優化
work_processers CPU * [1,2]; #工作進程數
worker_rlimit_nofile 102400; #最大打開連接符
worker_connections 65535; #每進程最
iii、Linux內核參數
net.ipv4.tcp_max_tw_buckets = 6000
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1
net.core.somaxconn = 262144
四、高可用模式
i、Nginx+keepalived 主從配置
這種方案,使用一個vip地址,前端使用2臺機器,一臺做主,一臺做備,但同時只有一臺機器工作,另一臺備份機器在主機器不出現故障的時候,永遠處於浪費狀態,對於服務器不多的網站,該方案不經濟實惠。
ii、Nginx+keepalived 雙主配置
這種方案,使用兩個vip地址,前端使用2臺機器,互爲主備,同時有兩臺機器工作,當其中一臺機器出現故障,兩臺機器的請求轉移到一臺機器負擔,非常適合於當前架構環境。
主從配置安裝參考資料:https://blog.csdn.net/kity9420/article/details/80687032
雙主配置參考資料:https://blog.csdn.net/u011781521/article/details/80495294