Nginx (讀作”engine X”) 由Igor Sysoev(俄羅斯)于2005年編寫啊易,是一個免費、開源饮睬、高性能的HTTP服務(wù)器和反向代理租谈,也可以作為一個IMAP/POP3代理服務(wù)器。
根據(jù) Netcraft 的 April 2015 Web Server Survey, 現(xiàn)在全世界14.48%的網(wǎng)站使用Nginx,而Apache占38.39%割去。
Nginx因為穩(wěn)定窟却,豐富的功能集,配置簡單呻逆,資源占用低而聞名世界夸赫。,目前使用最多的就是負載均衡咖城。
Nginx安裝
安裝位于官方倉庫的nginx 軟件包茬腿。
# pacman -S nginx //安裝位于官方倉庫的nginx 軟件包。
啟動服務(wù)
要啟動Nginx服務(wù),運行以下命令:
# systemctl start nginx
要Nginx服務(wù)開機時啟動,運行以下命令:
# systemctl enable nginx
http://127.0.0.1 的默認頁面是:
/usr/share/nginx/html/index.html
Nginx工作原理
Nginx由內(nèi)核和模塊組成宜雀,完成工作是通過查找配置文件將客戶端請求映射到一個location block(location是用于URL匹配的命令)切平,location配置的命令會啟動不同模塊完成工作。
Nginx模塊分為核心模塊辐董,基礎(chǔ)模塊和第三方模塊悴品。
核心模塊:HTTP模塊、EVENT模塊(事件)简烘、MAIL模塊苔严。
基礎(chǔ)模塊:HTTP Access模塊、HTTP FastCGI模塊夸研、HTTP Proxy模塊邦蜜、HTTP Rewrite模塊。
第三方模塊:HTTP Upstream Request Hash模塊亥至、Notice模塊、HTTP Access Key模塊贱迟。
性能優(yōu)勢
** web服務(wù)器**姐扮,處理靜態(tài)文件、索引文件以及自動索引效率高衣吠。
代理服務(wù)器茶敏,快速高效反向代理,提升網(wǎng)站性能缚俏。
負載均衡器惊搏,內(nèi)部支持Rails和PHP,也可支持HTTP代理服務(wù)器,對外進行服務(wù)忧换。同時支持簡單容錯和利用算法進行負載均衡恬惯。
性能方面,Nginx專門為性能設(shè)計亚茬,實現(xiàn)注重效率酪耳。采用Poll模型,可以支持更多的并發(fā)連接刹缝,并在大并發(fā)時占用很低內(nèi)存碗暗。
穩(wěn)定性方面颈将,采用分階段資源分配技術(shù),使CPU資源占用率低言疗。
高可用性方面晴圾,支持熱備,啟動迅速噪奄。
Nginx配置文件
/usr/local/nginx/conf/nginx.conf
配置文件主要由四部分組成:main(全區(qū)設(shè)置)疑务,server(主機配置),upstream(負載均衡服務(wù)器設(shè)置)梗醇,和location(URL匹配特定位置設(shè)置)知允。
1)全局變量
#Nginx的worker進程運行用戶以及用戶組
#user nobody nobody;
#Nginx開啟的進程數(shù)
worker_processes 1;
#worker_processes auto;
#以下參數(shù)指定了哪個cpu分配給哪個進程,一般來說不用特殊指定叙谨。如果一定要設(shè)的話温鸽,用0和1指定分配方式.
#這樣設(shè)就是給1-4個進程分配單獨的核來運行,出現(xiàn)第5個進程是就是隨機分配了手负。eg:
#worker_processes 4 #4核CPU
#worker_cpu_affinity 0001 0010 0100 1000;
nets
#定義全局錯誤日志定義類型涤垫,[debug|info|notice|warn|crit]
#error_log logs/error.log info;
#指定進程ID存儲文件位置
#pid logs/nginx.pid;
#一個nginx進程打開的最多文件描述符數(shù)目,理論值應(yīng)該是最多打開文件數(shù)(ulimit -n)與nginx進程數(shù)相除竟终,但是nginx分配請求并不是那么均勻蝠猬,所以最好與ulimit -n的值保持一致。
#vim /etc/security/limits.conf
# * soft nproc 65535
# * hard nproc 65535
# * soft nofile 65535
# * hard nofile 65535
worker_rlimit_nofile 65535;
2)事件配置
events {
#use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型是Linux 2.6以上版本內(nèi)核中的高性能網(wǎng)絡(luò)I/O模型统捶,如果跑在FreeBSD上面榆芦,就用kqueue模型。
use epoll;
#每個進程可以處理的最大連接數(shù)喘鸟,理論上每臺nginx服務(wù)器的最大連接數(shù)為worker_processes*worker_connections匆绣。理論值:worker_rlimit_nofile/worker_processes
#注意:最大客戶數(shù)也由系統(tǒng)的可用socket連接數(shù)限制(~ 64K),所以設(shè)置不切實際的高沒什么好處
worker_connections 65535;
#worker工作方式:串行(一定程度降低負載什黑,但服務(wù)器吞吐量大時崎淳,關(guān)閉使用并行方式)
#multi_accept on;
}
3)http參數(shù)
#文件擴展名與文件類型映射表
include mime.types;
#默認文件類型
default_type application/octet-stream;
#日志相關(guān)定義
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#定義日志的格式。后面定義要輸出的內(nèi)容愕把。
#1.$remote_addr 與$http_x_forwarded_for 用以記錄客戶端的ip地址拣凹;
#2.$remote_user :用來記錄客戶端用戶名稱;
#3.$time_local :用來記錄訪問時間與時區(qū)恨豁;
#4.$request :用來記錄請求的url與http協(xié)議嚣镜;
#5.$status :用來記錄請求狀態(tài);
#6.$body_bytes_sent :記錄發(fā)送給客戶端文件主體內(nèi)容大惺バ酢祈惶;
#7.$http_referer :用來記錄從那個頁面鏈接訪問過來的;
#8.$http_user_agent :記錄客戶端瀏覽器的相關(guān)信息
#連接日志的路徑,指定的日志格式放在最后捧请。
#access_log logs/access.log main;
#只記錄更為嚴重的錯誤日志凡涩,減少IO壓力
error_log logs/error.log crit;
#關(guān)閉日志
#access_log off;
#默認編碼
#charset utf-8;
#服務(wù)器名字的hash表大小
server_names_hash_bucket_size 128;
#客戶端請求單個文件的最大字節(jié)數(shù)
client_max_body_size 8m;
#指定來自客戶端請求頭的hearerbuffer大小
client_header_buffer_size 32k;
#指定客戶端請求中較大的消息頭的緩存最大數(shù)量和大小。
large_client_header_buffers 4 64k;
#開啟高效傳輸模式疹蛉。
sendfile on;
#防止網(wǎng)絡(luò)阻塞
tcp_nopush on;
tcp_nodelay on;
#客戶端連接超時時間活箕,單位是秒
keepalive_timeout 60;
#客戶端請求頭讀取超時時間
client_header_timeout 10;
#設(shè)置客戶端請求主體讀取超時時間
client_body_timeout 10;
#響應(yīng)客戶端超時時間
send_timeout 10;
#FastCGI相關(guān)參數(shù)是為了改善網(wǎng)站的性能:減少資源占用,提高訪問速度可款。
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;
#gzip模塊設(shè)置
#開啟gzip壓縮輸出
gzip on;
#最小壓縮文件大小
gzip_min_length 1k;
#壓縮緩沖區(qū)
gzip_buffers 4 16k;
#壓縮版本(默認1.1育韩,前端如果是squid2.5請使用1.0)
gzip_http_version 1.0;
#壓縮等級 1-9 等級越高,壓縮效果越好闺鲸,節(jié)約寬帶筋讨,但CPU消耗大
gzip_comp_level 2;
#壓縮類型,默認就已經(jīng)包含text/html摸恍,所以下面就不用再寫了悉罕,寫上去也不會有問題,但是會有一個warn立镶。
gzip_types text/plain application/x-javascript text/css application/xml;
#前端緩存服務(wù)器緩存經(jīng)過壓縮的頁面
gzip_vary on;
4)虛擬主機基本設(shè)置
#虛擬主機定義
server {
#監(jiān)聽端口
listen 80;
#訪問域名
server_name localhost;
#編碼格式壁袄,若網(wǎng)頁格式與此不同,將被自動轉(zhuǎn)碼
#charset koi8-r;
#虛擬主機訪問日志定義
#access_log logs/host.access.log main;
#對URL進行匹配
location / {
#訪問路徑媚媒,可相對也可絕對路徑
root html;
#首頁文件嗜逻。以下按順序匹配
index index.html index.htm;
}
#錯誤信息返回頁面
#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;
}
#訪問URL以.php結(jié)尾則自動轉(zhuǎn)交給127.0.0.1
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
#php腳本請求全部轉(zhuǎn)發(fā)給FastCGI處理
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#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;
#}
#禁止訪問.ht頁面 (需ngx_http_access_module模塊)
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
#HTTPS虛擬主機定義
# HTTPS server
#
#server {
# 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;
# }
#}
#vue配置
server {
listen 80;
server_name jcsd-cdn-monitor.jdcloud.com;
#charset koi8-r;
#access_log logs/host.access.log main;
root /root/dist;
location / {
try_files $uri $uri/ /index.html;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
5)Nignx狀態(tài)監(jiān)控
#Nginx運行狀態(tài),StubStatus模塊獲取Nginx自啟動的工作狀態(tài)(編譯時要開啟對應(yīng)功能)
#location /NginxStatus {
# #啟用StubStatus的工作訪問狀態(tài)
# stub_status on;
# #指定StubStaus模塊的訪問日志文件 可off
# access_log logs/Nginxstatus.log;
# #Nginx認證機制(需Apache的htpasswd命令生成)
# #auth_basic "NginxStatus";
# #用來認證的密碼文件
# #auth_basic_user_file ../htpasswd;
#}
訪問:http://IP/NginxStatus(測試就不加密碼驗證相關(guān))
active connections – 活躍的連接數(shù)量
server accepts handled requests — 總共處理了3個連接 , 成功創(chuàng)建3次握手, 總共處理了1個請求
reading — 讀取客戶端的連接數(shù).
writing — 響應(yīng)數(shù)據(jù)到客戶端的數(shù)量
waiting — 開啟 keep-alive 的情況下,這個值等于 active – (reading+writing), 意思就是 Nginx 已經(jīng)處理完正在等候下一次請求指令的駐留連接.
6)反向代理
#以下配置追加在HTTP的全局變量中
#啟動代理緩存功能
proxy_buffering on;
#nginx跟后端服務(wù)器連接超時時間(代理連接超時)
proxy_connect_timeout 5;
#后端服務(wù)器數(shù)據(jù)回傳時間(代理發(fā)送超時)
proxy_send_timeout 5;
#連接成功后缭召,后端服務(wù)器響應(yīng)時間(代理接收超時)
proxy_read_timeout 60;
#設(shè)置代理服務(wù)器(nginx)保存用戶頭信息的緩沖區(qū)大小
proxy_buffer_size 16k;
#proxy_buffers緩沖區(qū)栈顷,網(wǎng)頁平均在32k以下的話,這樣設(shè)置
proxy_buffers 4 32k;
#高負荷下緩沖大心涨怼(proxy_buffers*2)
proxy_busy_buffers_size 64k;
#設(shè)定緩存文件夾大小妨蛹,大于這個值,將從upstream服務(wù)器傳
proxy_temp_file_write_size 64k;
#反向代理緩存目錄
proxy_cache_path /data/proxy/cache levels=1:2 keys_zone=cache_one:500m inactive=1d max_size=1g;
#levels=1:2 設(shè)置目錄深度晴竞,第一層目錄是1個字符,第2層是2個字符
#keys_zone:設(shè)置web緩存名稱和內(nèi)存緩存空間大小
#inactive:自動清除緩存文件時間狠半。
#max_size:硬盤空間最大可使用值噩死。
#指定臨時緩存文件的存儲路徑(必須在同一分區(qū))
proxy_temp_path /data/proxy/temp;
#服務(wù)配置
server {
#偵聽的80端口
listen 80;
server_name localhost;
location / {
#反向代理緩存設(shè)置命令(proxy_cache zone|off,默認關(guān)閉所以要設(shè)置)
proxy_cache cache_one;
#對不同的狀態(tài)碼緩存不同時間
proxy_cache_valid 200 304 12h;
#設(shè)置以什么樣參數(shù)獲取緩存文件名
proxy_cache_key $host$uri$is_args$args;
#后端的Web服務(wù)器可以通過X-Forwarded-For獲取用戶真實IP
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#代理設(shè)置
proxy_pass http://IP;
#文件過期時間控制
expires 1d;
}
#配置手動清楚緩存(實現(xiàn)此功能需第三方模塊 ngx_cache_purge)
#http://www.123.com/2017/0316/17.html訪問
#http://www.123.com/purge/2017/0316/17.html清楚URL緩存
location ~ /purge(/.*) {
allow 127.0.0.1;
deny all;
proxy_cache_purge cache_one $host$1$is_args$args;
}
#設(shè)置擴展名以.jsp、.php神年、.jspx結(jié)尾的動態(tài)應(yīng)用程序不做緩存
location ~.*\.(jsp|php|jspx)?$ {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://IP;
}
7)負載均衡
#負載均衡服務(wù)器池
upstream my_server_pool {
#調(diào)度算法
#1.輪循(默認)(weight輪循權(quán)值)
#2.ip_hash:根據(jù)每個請求訪問IP的hash結(jié)果分配已维。(會話保持)
#3.fair:根據(jù)后端服務(wù)器響應(yīng)時間最短請求。(upstream_fair模塊)
#4.url_hash:根據(jù)訪問的url的hash結(jié)果分配已日。(需hash軟件包)
#參數(shù):
#down:表示不參與負載均衡
#backup:備份服務(wù)器
#max_fails:允許最大請求錯誤次數(shù)
#fail_timeout:請求失敗后暫停服務(wù)時間垛耳。
server 192.168.1.109:80 weight=1 max_fails=2 fail_timeout=30;
server 192.168.1.108:80 weight=2 max_fails=2 fail_timeout=30;
}
#負載均衡調(diào)用
server {
...
location / {
proxy_pass http://my_server_pool;
}
}
8)URL重寫
#根據(jù)不同的瀏覽器URL重寫
if($http_user_agent ~ Firefox){
rewrite ^(.*)$ /firefox/$1 break;
}
if($http_user_agent ~ MSIE){
rewrite ^(.*)$ /msie/$1 break;
}
#實現(xiàn)域名跳轉(zhuǎn)
location / {
rewrite ^/(.*)$ https://web8.example.com$1 permanent;
}
9)IP限制
#限制IP訪問
location / {
deny 192.168.0.2;
allow 192.168.0.0/24;
allow 192.168.1.1;
deny all;
}
10)Nginx相關(guān)命令
#啟動nginx
nginx
#關(guān)閉nginx
nginx -s stop
#平滑重啟
kill -HUP `cat /usr/local/nginx/logs/nginx.pid`
11)Nginx啟動腳本
#!/bin/bash
#chkconfig: 2345 80 90
#description:auto_run
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
# Check if user is root
if [ $(id -u) != "0" ]; then
echo "Error: You must be root to run this script!\n"
exit 1
fi
NGINXDAEMON=/usr/local/nginx/sbin/nginx
PIDFILE=/usr/local/nginx/logs/nginx.pid
function_start()
{
echo -en "\033[32;49;1mStarting nginx......\n"
echo -en "\033[39;49;0m"
if [ -f $PIDFILE ]; then
printf "Nginx is runing!\n"
exit 1
else
$NGINXDAEMON
printf "Nginx is the successful start!\n"
fi
}
function_stop()
{
echo -en "\033[32;49;1mStoping nginx......\n"
echo -en "\033[39;49;0m"
if [ -f $PIDFILE ]; then
kill `cat $PIDFILE`
printf "Nginx program is stoped\n"
else
printf "Nginx program is not runing!\n"
fi
}
function_reload()
{
echo -en "\033[32;49;1mReload nginx......\n"
echo -en "\033[39;49;0m"
function_stop
function_start
}
function_restart()
{
echo -en "\033[32;49;1mRestart nginx......\n"
echo -en "\033[39;49;0m"
printf "Reload Nginx configure...\n"
$NGINXDAEMON -t
kill -HUP `cat $PIDFILE`
printf "Nginx program is reloding!\n"
}
function_kill()
{
killall nginx
}
function_status()
{
if ! ps -ef|grep -v grep|grep 'nginx:' > /dev/null 2>&1
then
printf "Nginx is down!!!\n"
else
printf "Nginx is running now!\n"
fi
}
if [ "$1" = "start" ]; then
function_start
elif [ "$1" = "stop" ]; then
function_stop
elif [ "$1" = "reload" ]; then
function_reload
elif [ "$1" = "restart" ]; then
function_restart
elif [ "$1" = "kill" ]; then
function_kill
elif [ "$1" = "status" ]; then
function_status
else
echo -en "\033[32;49;1m Usage: nginx {start|stop|reload|restart|kill|status}\n"
echo -en "\033[39;49;0m"
fi