Nginx(“engine x”)是一個開源的,支持高性能、高併發的WWW服務和代理服務軟件。它還具有反向代理負載均衡功能和緩存服務功能。
1 Nginx的幾個常見的重要特性
1、支持高併發:能支持幾萬併發連接(特別是靜態小文件業務環境)
2、資源消耗少:在3萬併發連接下,開啓10個Nginx線程消耗的內存不到200MB
3、可以做HTTP反向代理及加速緩存,即負載均衡功能,內置對RS節點服務器健康檢查功能,這相當於專業的Haproxy軟件或LVS的功能
4、具備Squid等專業緩存軟件等的緩存功能
5、支持異步網絡I/O事件模型epoll(linux2.6+)
2 Nginx軟件的主要企業功能應用
1)作爲web服務軟件
支持高性能、高併發,與Apache相比,Nginx能夠支持更多的併發連接訪問,但佔用的資源卻更少,效率更高,幾乎不遜色於Apache
2)反向代理或負載均衡服務
在方向代理或負載均衡服務方面,Nginx可以作爲web服務、PHP等動態服務及Memcached緩存的代理服務器,它具有類似專業反向代理軟件(如Haproxy)的功能,也是一個郵件代理服務軟件,支持TCP的代理。
3)前端業務數據緩存服務
在web緩存服務方面,Nginx可以通過自身的proxy_cache模塊實現類Squid等專業緩存軟件的功能
3 Nginx Web服務
3.1 Nginx Web服務介紹
作爲web服務器的主要應用場景:
1)使用Nginx運行HTML、JS、CSS、小圖片等靜態數據(類似Lighttpd)
2)Nginx結合FastCGI運行PHP等動態程序(使用fastcgi_pass方式)
3)Nginx結合Tomcat/Resin等支持Java動態程序(常用proxy_pass方式)
3.2 爲什麼Nginx總體性能比Apache高
Nginx使用epoll和kqueue(freebsd)異步網絡I/O模型,而Apache使用的是傳統的select模型。目前Linux下能夠承受高併發訪問的Squid、Memcached軟件採用的都是epoll模型
處理大量連接的讀寫時,select網絡I/O模型比較低效。而epoll卻很高效
宿管比喻:
Select:帶着你到各個房間挨個去找人,知道找到人爲止。
Epoll:會先記下每個人住的房間號,當你找人時,只需要告訴你住哪個房間即可,不用親自帶着你滿宿舍樓找人了。
如果同時來了100個人找人,效率差別就很明顯了。
3.3 如何正確選擇web服務器
靜態業務:若是高併發場景,儘量採用Nginx或Lighttpd,二者首選Ngingx
動態業務:理論上採用Nginx和Apache均可,建議選擇Nginx,爲了避免相同業務的服務軟件多樣化,增加維護成本。動態業務可以由Nginx兼做前端代理,再轉發到後端相應的服務器進行處理。
既有靜態業務又有動態業務:採用Nginx
如果併發不是很大,又對Apache熟悉,也可以選擇Apache,總之選擇熟悉的。
4 編譯安裝Nginx
4.1 檢查系統版本
[root@lnmp02 ~]# cat /etc/redhat-release CentOS release 6.5 (Final) [root@lnmp02 ~]# uname -r 2.6.32-431.el6.x86_64 [root@lnmp02 ~]# uname -m x86_64
4.2 安裝Nginx所需的 pcre pcre-devel
[root@lnmp02 ~]# rpm -qa pcre pcre-devel pcre-7.8-6.el6.x86_64 [root@lnmp02 ~]# yum install pcre pcre-devel -y [root@lnmp02 ~]# rpm -qa pcre pcre-devel pcre-7.8-7.el6.x86_64 pcre-devel-7.8-7.el6.x86_64
4.3 安裝 openssl-devel openssl
[root@lnmp02 ~]# rpm -qa openssl-devel openssl openssl-1.0.1e-15.el6.x86_64 [root@lnmp02 ~]# yum install openssl-devel -y [root@lnmp02 ~]# rpm -qa openssl-devel openssl openssl-1.0.1e-57.el6.x86_64 openssl-devel-1.0.1e-57.el6.x86_64
4.4 安裝 Ngnix
下載Nginx軟件
[root@lnmp02 ~]# rpm -qa ngnix [root@lnmp02 tools]# wget -q http://nginx.org/download/nginx-1.6.3.tar.gz [root@lnmp02 tools]# ls -l 總用量 788 -rw-r--r-- 1 root root 805253 4月 8 2015 nginx-1.6.3.tar.gz
解壓Nginx包
[root@lnmp02 tools]# tar xf nginx-1.6.3.tar.gz [root@lnmp02 tools]# cd nginx-1.6.3 [root@lnmp02 nginx-1.6.3]# ls auto CHANGES CHANGES.ru conf configure contrib html LICENSE man README src [root@lnmp02 nginx-1.6.3]# tree|wc -l 404
創建nginx用戶 設置安裝具體細節
[root@lnmp02 nginx-1.6.3]# useradd nginx -s /sbin/nologin -M [root@lnmp02 nginx-1.6.3]# ./configure --user=nginx --group=nginx --prefix=/application/nginx-1.6.3/ --with-http_stub_status_module --with-http_ssl_module [root@lnmp02 nginx-1.6.3]# make [root@lnmp02 nginx-1.6.3]# make install [root@lnmp02 nginx-1.6.3]# echo $? 0
創建軟鏈接
[root@lnmp02 nginx-1.6.3]# cd .. [root@lnmp02 tools]# ln -s /application/nginx-1.6.3/ /application/nginx [root@lnmp02 tools]# ls -l /application/ 總用量 4 lrwxrwxrwx 1 root root 25 6月 24 16:58 nginx -> /application/nginx-1.6.3/ drwxr-xr-x 6 root root 4096 6月 24 16:57 nginx-1.6.3
安裝搞定,啓動並檢查安裝結果
啓動前檢查語法 [root@lnmp02 tools]# /application/nginx/sbin/nginx -t nginx: the configuration file /application/nginx-1.6.3//conf/nginx.conf syntax is ok nginx: configuration file /application/nginx-1.6.3//conf/nginx.conf test is successful 啓動服務 [root@lnmp02 tools]# /application/nginx/sbin/nginx 查看nginx服務是否啓動成功 [root@lnmp02 tools]# ps -ef|grep nginx|grep -v grep root 7125 1 0 17:05 ? 00:00:00 nginx: master process /application/nginx/sbin/nginx nginx 7126 7125 0 17:05 ? 00:00:00 nginx: worker process [root@lnmp02 tools]# ss -lntup|grep nginx tcp LISTEN 0 128 *:80 *:* users:(("nginx",7125,6),("nginx",7126,6)) [root@lnmp02 tools]# netstat -lntup|grep nginx tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 7125/nginx 用curl命令檢測是否成功 [root@lnmp02 tools]# curl 127.0.0.1 <!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> 《=============看到此處歡迎說明成功了,也可以用瀏覽器輸出服務器地址來檢測,也可以用wget命令測試 <style> body { width: 35em; margin: 0 auto; font-family: Tahoma, Verdana, Arial, sans-serif; } </style> </head> <body> <h1>Welcome to nginx!</h1> <p>If you see this page, the nginx web server is successfully installed and working. Further configuration is required.</p> <p>For online documentation and support please refer to <a href="http://nginx.org/">nginx.org</a>.<br/> Commercial support is available at <a href="http://nginx.com/">nginx.com</a>.</p> <p><em>Thank you for using nginx.</em></p> </body> </html>
5 Nginx深入剖析
5.1 Nginx http功能模塊彙總
http_core_module | 包括一些核心的http參數配置 |
http_access_module | 訪問控制模塊 |
http_gzip_module | 壓縮模塊 |
http_fastcgi_module | fastcgi模塊 |
http_proxy_module | 代理模塊 |
http_upstream_module | 負載均衡模塊 |
http_rewrite_module | URL地址重寫模塊 |
http_limit_conn_module | 限制用戶的併發連接以及請求數 |
http_limit_req_module | 定義的key限制nginx請求過程的速率 |
http_log_module | 訪問日誌模塊,指定格式記錄nginx客戶訪問日誌 |
http_auth_basic_module | web認證,設置web用戶通過賬號和密碼訪問nginx |
http_ssl_module | 加密的http |
http_stub_status_module | 記錄nginx基本訪問狀態信息 |
5.2 Nginx的目錄結構
5.3 主配置文件nginx.conf
1 2 #user nobody; 3 worker_processes 1; 4 5 #error_log logs/error.log; 6 #error_log logs/error.log notice; 7 #error_log logs/error.log info; 8 9 #pid logs/nginx.pid; #1~9爲Main區,核心功能模塊 10 11 12 events { 13 worker_connections 1024; #12~13行爲events區,核心功能模塊 14 } 15 16 17 http { #17行是http區開始,http核心模塊 18 include mime.types; 19 default_type application/octet-stream; 20 21 #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' 22 # '$status $body_bytes_sent "$http_referer" ' 23 # '"$http_user_agent" "$http_x_forwarded_for"'; 24 25 #access_log logs/access.log main; 26 27 sendfile on; 28 #tcp_nopush on; 29 30 #keepalive_timeout 0; 31 keepalive_timeout 65; 32 33 #gzip on; 34 35 server { #35~46爲server區塊 36 listen 80; 37 server_name localhost; 38 39 #charset koi8-r; 40 41 #access_log logs/host.access.log main; 42 43 location / { #location區塊 44 root html; 45 index index.html index.htm; 46 } 47 } 48 } #http區塊結束
整個Nginx配置文件的核心框架如下:
worker_processes 1; events { worker_connections 1024; } http { include mime.types; server { listen 80; server_name localhost; location / { root html; index index.html index.htm; } } }
關於配置文件的詳細解釋
[root@lnmp02 ~]# egrep -v "#|^$" /application/nginx/conf/nginx.conf.default worker_processes 1; <===worker進程數量 events { <===事件區塊開始 worker_connections 1024; <===每個worker進程支持的最大連接數 } <===事件區塊結束 http { <===http區塊開始 include mime.types; <===Nginx支持的媒體類型庫文件 default_type application/octet-stream; <===默認的媒體類型 sendfile on; <===開啓高效傳輸模式 keepalive_timeout 65; <===連接超時 server { <===第一個server區塊開始,表示一個虛擬主機站點 listen 80; <===提供服務的端口,默認80 server_name localhost; <===提供服務的域名主機名 location / { <===第一個location區塊開始 root html; <===站點的根目錄,相當於Nginx的安裝目錄 index index.html index.htm; <===默認首頁文件,多個用空格分開 } <===第一個location區塊結束 error_page 500 502 503 504 /50x.html; <===出現對應的狀態碼時,使用50x.html迴應客戶 location = /50x.html { <===location區塊開始,訪問50x.html root html; <===指定對應的站點目錄爲html } } } <===http區塊結束
6 Nginx虛擬主機配置
6.1 Nginx虛擬主機配置(以基於域名的虛擬主機爲例)
1、基於域名的虛擬主機*****
2、基於端口的虛擬主機***
3、基於IP的虛擬主機
增加新域名對應的配置
[
root@lnmp02 tools]# cd /application/nginx [root@lnmp02 nginx]# cd conf/ [root@lnmp02 conf]# egrep -v "#|^$" nginx.conf.default >nginx.conf [root@lnmp02 conf]# vim nginx.conf worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 80; 《=============若配置基於端口或者IP的虛擬主機,在此修改端口號或者添加IP server_name www.etiantian123.org; location / { root html/www; index index.html index.htm; } } server { listen 80; 《=============例如:基於IP:192.168.4.122:80 server_name bbs.etiantian123.org; location / { root html/bbs; index index.html index.htm; } } }
檢查語法
[root@lnmp02 conf]# /application/nginx/sbin/nginx -t nginx: the configuration file /application/nginx-1.6.3//conf/nginx.conf syntax is ok nginx: configuration file /application/nginx-1.6.3//conf/nginx.conf test is successful
創建域名對應的站點目錄及文件
[root@lnmp02 conf]# mkdir ../html/{www,bbs} [root@lnmp02 conf]# tree ../html/ ../html/ ├── 50x.html ├── bbs ├── index.html └── www [root@lnmp02 conf]# echo "www.etiantian.org" >../html/www/index.html [root@lnmp02 conf]# echo "bbs.etiantian.org" >../html/bbs/index.html [root@lnmp02 conf]# cat ../html/{www,bbs}/index.html www.etiantian.org bbs.etiantian.org
平滑啓動服務
[root@lnmp02 conf]# /application/nginx/sbin/nginx -s reload
修改/etc/hosts
[root@lnmp02 conf]# vim /etc/hosts 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 192.168.4.122 lnmp02 192.168.4.122 www.etiantian123.org 192.168.4.122 bbs.etiantian123.org
用curl測試是否成功
[root@lnmp02 conf]# curl www.etiantian123.org www.etiantian.org [root@lnmp02 conf]# curl bbs.etiantian123.org bbs.etiantian.org 如果是windows測試,則需要修改/etc/hosts文件,格式和linux一致
規範優化Nginx配置文件
[root@lnmp02 conf]# cat nginx.conf worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; #nginx vhosts config include extra/www.conf; include extra/bbs.conf; include extra/blog.conf; } [root@lnmp02 conf]# mkdir extra [root@lnmp02 conf]# sed -n '10,17p' nginx.conf.ori.1 server { listen 80; server_name www.etiantian123.org; location / { root html/www; index index.html index.htm; } } [root@lnmp02 conf]# sed -n '10,17p' nginx.conf.ori.1 >extra/www.conf [root@lnmp02 conf]# cat extra/www.conf server { listen 80; server_name www.etiantian123.org; location / { root html/www; index index.html index.htm; } } [root@lnmp02 conf]# sed -n '18,25p' nginx.conf.ori.1 >extra/bbs.conf [root@lnmp02 conf]# sed -n '26,33p' nginx.conf.ori.1 server { listen 80; server_name blog.etiantian123.org; location / { root html/blog; index index.html index.htm; } } [root@lnmp02 conf]# sed -n '26,33p' nginx.conf.ori.1 >extra/blog.conf
配置好檢查一下
[root@lnmp02 conf]# cat extra/blog.conf [root@lnmp02 conf]# cat extra/bbs.conf [root@lnmp02 conf]# cat extra/www.conf
重啓下服務
[root@lnmp02 conf]# ../sbin/nginx -t nginx: the configuration file /application/nginx-1.6.3//conf/nginx.conf syntax is ok nginx: configuration file /application/nginx-1.6.3//conf/nginx.conf test is successful [root@lnmp02 conf]# ../sbin/nginx -s reload
6.2 Nginx虛擬主機的別名配置
[root@lnmp02 conf]# cat extra/www.conf server { listen 80; server_name www.etiantian123.org etiantian123.org; <===直接在域名後面添加別名 location / { root html/www; index index.html index.htm; } }
在/etc/hosts添加別名的解析
[root@lnmp02 conf]# cat /etc/hosts 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 192.168.4.122 lnmp02 192.168.4.122 www.etiantian123.org etiantian123.org <=======添加別名 192.168.4.122 bbs.etiantian123.org 192.168.4.122 blog.etiantian123.org 192.168.4.122 status.etiantian123.org
檢查並重新加載服務
[root@lnmp02 conf]# ../sbin/nginx -t [root@lnmp02 conf]# ../sbin/nginx -s reload
6.3 Nginx狀態信息功能
[root@lnmp02 conf]# cat extra/status.conf ##status server { listen 80; server_name status.etiantian123.org; location / { stub_status on; <============打開狀態信息開關 access_log off; } }
增加包含文件的配置到主配置文件
[root@lnmp02 conf]# cat nginx.conf worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; #nginx vhosts config include extra/www.conf; include extra/bbs.conf; include extra/blog.conf; include extra/status.conf; <============增加status配置
檢查語法重啓服務
[root@lnmp02 conf]# ../sbin/nginx -t [root@lnmp02 conf]# ../sbin/nginx -s reload
6.4 爲Nginx增加錯誤日誌配置
[root@lnmp02 conf]# cat nginx.conf worker_processes 1; error_log logs/error.log; #<=======默認配置這一行即可 events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; #nginx vhosts config include extra/www.conf; include extra/bbs.conf; include extra/blog.conf; include extra/status.conf; }
6.5 Nginx訪問日誌
訪問日誌的配置
[root@lnmp02 conf]# vim nginx.conf worker_processes 1; error_log logs/error.log; events { worker_connections 1024; } 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"'; #增加這三行 sendfile on; keepalive_timeout 65; #nginx vhosts config include extra/www.conf; include extra/bbs.conf; include extra/blog.conf; include extra/status.conf; }
然後在每個虛擬主機裏進行配置(以www爲例子)
[root@lnmp02 conf]# vim extra/www.conf server { listen 80; server_name www.etiantian123.org etiantian123.org; location / { root html/www; index index.html index.htm; } access_log logs/access_www.log main; 《=====增加一行日誌配置,main是爲日誌格式指定的標籤 }
檢查並重啓服務
[root@lnmp02 conf]# ../sbin/nginx -t nginx: the configuration file /application/nginx-1.6.3//conf/nginx.conf syntax is ok nginx: configuration file /application/nginx-1.6.3//conf/nginx.conf test is successful [root@lnmp02 conf]# ../sbin/nginx -s reload
用瀏覽器模擬用戶訪問生成日誌,在服務器上查詢結果
[root@lnmp02 conf]# tail -1 ../logs/access_www.log 192.168.4.101 - - [25/Jun/2017:00:54:50 +0800] "GET /favicon.ico HTTP/1.1" 404 570 "-" "Mozilla/4.0 (compatible; MSIE 7.0; LBBROWSER)" "-"
在高併發場景下提升網站訪問性能,可以加上buffer和flush選項參數,打包
access_log logs/access_www.log main gzip buffer=32K flush=5s
Ngnix訪問日誌輪詢切割
創建腳本
[root@lnmp02 conf]# vim /server/scripts/cut_nginx_log.sh
#!/bin/sh Dateformat=`date +%Y%m%d` Basedir="/application/nginx" Nginxlogdir="$Basedir/logs" Logname="access_www" [ -d $Nginxlogdir ] && cd $Nginxlogdir||exit 1 [ -f ${Logname}.log ]||exit 1 /bin/mv ${Logname}.log ${Dateformat}_${Logname}.log #/bin/mv access_bbs.log ${Dateformat}_access_bbs.log #/bin/mv access_blog.log ${Dateformat}_access_blog.log $Basedir/sbin/nginx -s reload
通過定時任務實現每天0點執行/server/scripts/cut_nginx_log.sh來切割日誌
[root@lnmp02 conf]# crontab -e #########nginx訪問日誌切割################ 00 00 * * * /bin/sh /server/scripts/cut_nginx_log.sh &>/dev/null
測試效果
[root@lnmp02 logs]# /bin/sh /server/scripts/cut_nginx_log.sh [root@lnmp02 logs]# ll 總用量 100 -rw-r--r-- 1 root root 1458 6月 25 00:54 20170625_access_www.log -rw-r--r-- 1 root root 40537 6月 25 00:54 access.log -rw-r--r-- 1 root root 0 6月 25 01:13 access_www.log -rw-r--r-- 1 root root 44005 6月 25 01:13 error.log -rw-r--r-- 1 root root 5 6月 24 17:05 nginx.pid
7 Nginx rewrite
指令語法:rewrite regex replacement [flag]
rewrite ^/ (.*) http://www.etiantian.org/$1 permanent;
flag標記說明
flag標記符號 | 說明 |
last | 本條規則匹配完成後,繼續向下匹配新的location URI規則 |
break | 本條規則匹配完成後即終止,不再匹配後面的任何規則 |
redirect | 返回302臨時重定向,瀏覽器顯示跳轉後的URL地址 |
permanent | 返回301永久重定向,瀏覽器顯示跳轉後的URL地址 |
7.1 301跳轉
[root@lnmp02 conf]# vim extra/www.conf server { listen 80; server_name etiantian123.org; rewrite ^/ (.*) http://www.etiantian123.org/$1 permanent; #當用戶訪問etiantian123.org及下面的任意內容時,都會通過這條rewrite跳轉到www.etiantian123.org對應的地址 } server { listen 80; server_name www.etiantian123.org; location / { root html/www; index index.html index.htm; } access_log logs/access_www.log main; }
7.2 不同域名的URL跳轉
實現訪問http://blog.etiantian123.org時跳轉到
http://www.etiantian123.org/blog/wangxin.html
跳轉前,http://blog.etiantian123.org對應的站點配置如下:
[root@lnmp02 conf]# vim extra/blog.conf server { listen 80; server_name blog.etiantian123.org; location / { root html/blog; index index.html index.htm; } if ( $http_host ~* “^(.*)\.etiantian123\.org$” ) { set $domain $1; rewrite ^(.*) http://www.etiantian123.org/$domain/wangxin.html break; } }
要配置的規則內容爲:
if ( $http_host ~* “^(.*)\.etiantian123\.org$” ) { set $domain $1; rewrite ^(.*) http://www.etiantian123.org/$domain/wangxin.html break; }
跳轉後,http://www.etiantian123.org/blog/wangxin.html地址對應的站點配置如下
[root@lnmp02 conf]# vim extra/www.conf server { listen 80; server_name www.etiantian123.org; location / { root html/www; index index.html index.htm; } access_log logs/access_www.log main; }
8 Nginx 訪問認證
虛擬主機的配置
[root@lnmp02 nginx]# vim conf/extra/www.conf server { listen 80; server_name www.etiantian123.org etiantian123.org; location / { root html/www; index index.html index.htm; auth_basic "wangxin test"; auth_basic_user_file /application/nginx/conf/htpasswd; } access_log logs/access_www.log main; }
設置帳號密碼,並修改權限
[root@lnmp02 nginx]# yum install -y httpd [root@lnmp02 nginx]# which htpasswd /usr/bin/htpasswd [root@lnmp02 nginx]# htpasswd -bc /application/nginx/conf/htpasswd wangxian 123456 Adding password for user wangxian [root@lnmp02 nginx]# chmod 400 /application/nginx/conf/htpasswd [root@lnmp02 nginx]# chown nginx /application/nginx/conf/htpasswd [root@lnmp02 nginx]# cat /application/nginx/conf/htpasswd wangxian:K4zAKSh.uY.sY ç===密碼是加密的
檢查語法,重啓服務
[root@lnmp02 nginx]# /application/nginx/sbin/nginx -t nginx: the configuration file /application/nginx-1.6.3//conf/nginx.conf syntax is ok nginx: configuration file /application/nginx-1.6.3//conf/nginx.conf test is successful [root@lnmp02 nginx]# /application/nginx/sbin/nginx -s reload