一、Nginx介紹
Nginx是由俄羅斯軟體工程師Igor Sysoev開發的一個高性能的HTTP和反向代理伺服器,具備IMAP/POP3和SMTP伺服器功能,Nginx最大的特點是對高并發的支援和高效的負載均衡,在高并發的需求場景下,是Apache伺服器不錯的替代品。目前,包括新浪、騰訊等知名網站都已使用Nginx作為Web應用伺服器。下面我簡單介紹一下:
nginx是一個高性能的Web和反向代理伺服器,它具有很多非常優越的特性;
作為Web伺服器;相比較與Apache,Nginx使用更少的資源,支援更多的并發連接配接,展現更高的效率,這點使Nginx尤為受到虛拟主機提供商的歡迎,能夠支援高達50000個并發的連接配接數的響應。
作為負載均衡伺服器器:Nginx既可以在内部直接支援Rails和PHP,也可以支援作為HTTP代理伺服器對外驚醒服務,Nginx用C語言編寫,不論是系統資源開銷還是CPU使用效率都比Perlbal要好的多。
作為郵件代理伺服器,Nginx同時也是一個非常優秀的郵件代理伺服器(最早開發這個産品的目的之一也是作為郵件代理伺服器),Last.fm描述了成功并且美妙的使用經驗。
Nginx安裝非常簡單,配置檔案非常簡介(還能夠支援perl文法),Bugs非常少的伺服器:Nginx啟動特别容易,并且幾乎可以做到7*24不間斷運作,即使運作數月也不需要重新啟動。還能夠在不間斷服務的情況下進行軟體版本平滑更新。
二、軟體獲得及幫助文檔
官方位址:http://nginx.org
下載下傳穩定版本:http://nginx.org/download/nginx-1.8.0.tar.gz
幫助文檔:http://nginx.org/en/docs
編譯參數說明:http://nginx.org/en/docs/configure.html
三、Nginx的功能
1、Nginx的特性
子產品化設計、較好的擴充性
高可靠性:一個master啟動一或多個worker,每個worker響應多個請求
低記憶體消耗:10000個keepalive連接配接在Nginx中僅消耗2.5MB記憶體(官方資料)
支援熱部署:不停機更新配置檔案、更新日志檔案、更新伺服器程式版本
2、Nginx的基本功能
靜态web資源伺服器,能夠緩存打開的檔案描述符
支援http/imap/pop3/smtp的反向代理;支援緩存、負載均衡
支援fastcgi(fpm)
子產品化,非DSO機制,支援過濾器zip壓縮,SSI以及圖像大小調整
支援SSL
3、Nginx的擴充功能
基于名稱和IP的虛拟主機
支援keepalive的保持機制
支援平滑更新
定制通路日志,支援使用日志緩存區提高日志存儲性能
支援url rewrite
支援路徑别名(root或alias指定)
支援基于IP以及使用者的通路控制
支援傳輸速率限制,并發限制
4、Nginx的基本架構
一個master程序,生成一個或者多個worker程序,每個worker響應多個請求
事件驅動:epoll,kqueue,poll,select,rt signals
支援sendfile,sendfile64
支援AIO
支援mmap
5、Nginx子產品類型
Nginx core module: nginx的核心子產品
Standard HTTP modules:nginx的标準子產品
Optional HTTP modules:nginx的可選子產品
Mail modules :nginx的郵件子產品
3rd party modules:nginx的第三方子產品
6、Nginx程序詳解
主程序主要完成如下工作:
讀取并驗正配置資訊;
建立、綁定及關閉套接字;
啟動、終止及維護worker程序的個數;
無須中止服務而重新配置工作特性;
控制非中斷式程式更新,啟用新的二進制程式并在需要時復原至老版本;
重新打開日志檔案,實作日志滾動;
編譯嵌入式perl腳本;
worker程序主要完成的任務包括:
接收、傳入并處理來自用戶端的連接配接;
提供反向代理及過濾功能;
nginx任何能完成的其它任務;
cache loader程序主要完成的任務包括:
檢查緩存存儲中的緩存對象;
使用緩存中繼資料建立記憶體資料庫;
cache manager程序的主要任務:
緩存的失效及過期檢驗;
四、Nginx安裝配置
1、安裝依賴包(CentOS 6.7)
[root@mail soft]# yum -y groupinstall "Development tools,Server platform development,Desktop platform development"
[root@mail soft]# yum -y install pcre-devel openssl-devel
2、編譯安裝Nginx
[root@mail soft]# tar xf nginx-1.8.0.tar.gz
[root@mail soft]# cd nginx-1.8.0
[root@mail nginx-1.8.0]# groupadd -r nginx
[root@mail nginx-1.8.0]# useradd -g nginx -s /sbin/nologin -M nginx
[root@mail nginx-1.8.0]# ./configure \
--prefix=/usr/local/nginx \
--sbin-path=/usr/sbin/nginx \
--conf-path=/etc/nginx/nginx.conf \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--pid-path=/var/run/nginx/nginx.pid \
--lock-path=/var/lock/nginx.lock \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_flv_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--http-client-body-temp-path=/var/tmp/nginx/client/ \
--http-proxy-temp-path=/var/tmp/nginx/proxy/ \
--http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \
--http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \
--http-scgi-temp-path=/var/tmp/nginx/scgi \
--with-pcre
[root@mail nginx-1.8.0]# make && make install
##注意:編譯後有些檔案夾不會自動建立
[root@mail nginx-1.8.0]# mkdir -pv /var/tmp/nginx/{client,proxy,fcgi,uwsgi,scgi}
mkdir: created directory `/var/tmp/nginx'
mkdir: created directory `/var/tmp/nginx/client'
mkdir: created directory `/var/tmp/nginx/proxy'
mkdir: created directory `/var/tmp/nginx/fcgi'
mkdir: created directory `/var/tmp/nginx/uwsgi'
mkdir: created directory `/var/tmp/nginx/scgi'
這裡的二進制檔案是直接指定在PATH環境變量裡面的,所有可以直接使用,不用導出:
配置vim,使其編輯nginx配置檔案時文法着色,預設沒有
[root@mail nginx-1.8.0]# cd
[root@mail ~]# mkdir .vim
[root@mail ~]# cp -ra /u01/soft/nginx-1.8.0/contrib/vim/* .vim
[root@mail ~]# ls .vim
ftdetect indent syntax
編寫啟動腳本:
[root@mail ~]# vim /etc/rc.d/init.d/nginx
#!/bin/sh
#
# nginx - this script starts and stops the nginx daemin
#
# chkconfig: - 85 15
# description: Nginx is an HTTP(S) server, HTTP(S) reverse \
# proxy and IMAP/POP3 proxy server
# processname: nginx
# config: /etc/nginx/nginx.conf
# pidfile: /var/run/nginx.pid
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0
nginx="/usr/sbin/nginx"
prog=$(basename $nginx)
NGINX_CONF_FILE="/etc/nginx/nginx.conf"
lockfile=/var/lock/subsys/nginx
start() {
[ -x $nginx ] || exit 5
[ -f $NGINX_CONF_FILE ] || exit 6
echo -n $"Starting $prog: "
daemon $nginx -c $NGINX_CONF_FILE
retval=$?
echo
[ $retval -eq 0 ] && touch $lockfile
return $retval
}
stop() {
echo -n $"Stopping $prog: "
killproc $prog -QUIT
retval=$?
echo
[ $retval -eq 0 ] && rm -f $lockfile
return $retval
}
restart() {
configtest || return $?
stop
start
}
reload() {
configtest || return $?
echo -n $"Reloading $prog: "
killproc $nginx -HUP
RETVAL=$?
echo
}
force_reload() {
restart
}
configtest() {
$nginx -t -c $NGINX_CONF_FILE
}
rh_status() {
status $prog
}
rh_status_q() {
rh_status >/dev/null 2>&1
}
case "$1" in
start)
rh_status_q && exit 0
$1
;;
stop)
rh_status_q || exit 0
$1
;;
restart|configtest)
$1
;;
reload)
rh_status_q || exit 7
$1
;;
force-reload)
force_reload
;;
status)
rh_status
;;
condrestart|try-restart)
rh_status_q || exit 0
;;
*)
echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-
reload|configtest}"
exit 2
esac
[root@mail ~]# chmod +x /etc/rc.d/init.d/nginx #添加可執行權限
[root@mail ~]# chkconfig --add nginx #添加到服務清單
[root@mail ~]# chkconfig nginx on #設定開機自啟動
[root@mail ~]# service nginx start #啟動nginx
Starting nginx: [ OK ]
[root@mail ~]# ss -tnl #檢視是否監聽80端口
[root@mail ~]# ss -tnl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:80 *:*
LISTEN 0 128 :::22 :::*
LISTEN 0 128 *:22 *:*
##檢視頁面
[root@mail ~]# curl http://localhost
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<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>
#######################編譯安裝已經完成。
配置檔案介紹
主要有兩部分:分别是
main:主體部分
http{}:虛拟主機配置部分
配置指令主要以分号結尾;配置文法:directive value1 [value2 ....]
支援使用的變量
子產品内置的變量
自定義變量:set var_name value
主配置段的指令類别:
用于調試和定位問題:
(1)daemon [on|off]: 是否以守護程序的方式啟動nginx;
(2)master_press [on|off]: 是否以master/worker模型來運作nginx;
(3)error_log /path/to/error_loglevel: 指明錯誤日志檔案級别,處于調試目的,可以使用debug級别,但次級别隻有在編譯nginx時使用了--with-debug選項才有效 ;
正常運作必備的配置:
(1)user USERNAME [GROUPNAME]:指定運作worker的使用者和使用者組;例如 user nginx nginx
(2)pid /path/to/nginx.pid : 指定pid檔案
(3)worker_rlimit_nofile # : 指定一個worker程序能夠打開的最大檔案句柄數
(4)worker_rlimit_sigpending # : 指定每個使用者能夠發往worker信号的數量
優化性能相關的配置:
(1)worker_processes # :worker程序的個數,通常是cpu核心數減1
(2)worker_cpu_affinity cpuumask :綁定worker程序至指定的CPU上
(3)timer-resolution t :時間解析度,在x86伺服器上可以不用配置
(4)worker_priority NICE :調整nice值(-20,19);nice值越大,越優先配置設定cpu
事件相關的配置;
(1)accept_mutex [on|off] :内部調動使用者請求至各worker時的負載均衡鎖;啟用時表示能夠讓多個worker輪流的、序列化的響應請求
(2)lock_file /path/to/lock_file :指定鎖檔案
(3)accept_mutex_delay #ms: 取得負載均衡鎖的時間
(4)use [epoll|poll|select|rgsig]:定義使用的事件模型,建議讓nginx自動選擇
(5)worker_connections #:每個worker程序所能夠響應的最大并發請求數
五、Nginx的一些基本功能實作
1、基于使用者認證:
(1)、修改配置檔案
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
auth_basic "www.bjwf125.com";
auth_basic_user_file /www/html/.passwd;
}
}
(2)、建立文檔根目錄以及使用httpd-tools中的htpasswd工具建立使用者
[root@mail ~]# mkdir -pv /www/html
mkdir: created directory `/www'
mkdir: created directory `/www/html'
[root@mail ~]# echo "Welcome to bjwf125" > /www/html/index.html
[root@mail ~]# yum -y install httpd-tools
[root@mail ~]# htpasswd -c -m /www/html/.passwd centos #建立centos使用者
New password: #輸入密碼
Re-type new password: #再次輸入
Adding password for user centos
(3)、重新載入配置檔案
[root@mail ~]# nginx -t #檢查Nginx文法
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@mail ~]# service nginx reload #重新載入
2、基于IP認證
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
deny 192.168.9.0/24;
allow all;
}
}
3、基于gzip壓縮
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root /www/html;
index index.html index.htm;
gzip on;
gzip_http_version 1.0;
gzip_min_length 1000;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain application/xml text/css application/x-javascript text/xml
application/xml+rss text/javascript application/javascript application/json;
gzip_disable msie6 safari;
}
}
[root@mail ~]# nginx -t
[root@mail ~]# service nginx reload
[root@mail ~]# cp /etc/rc.d/rc.sysinit /www/html/zip.html
[root@mail ~]# ll /www/html/zip.html -h
-rwxr-xr-x 1 root root 20K Jan 13 10:01 /www/html/zip.html
4、定制響應頭部
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root /www/html;
index index.html index.htm;
expires 24h;
add_header bjwf125 mymail;
}
}
[root@mail ~]# nginx -t
[root@mail ~]# service nginx reload
5、URL重定向
文法格式:
rewrite grgex replacement [flages]
flages
last:一旦被目前規則比對并重寫後立即停止檢查其他後續的rewrite的規則,而後通過重寫後的規則重寫發起請求;
bleak:一旦被目前規則比對并重寫後立即停止後續的其他rewrite的規則,而後由nginx進行後續操作;
redirect:傳回302臨時重定向
permanent:傳回301永久重定向
例如:
[root@mail ~]# vim /etc/nginx/nginx.conf
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root /www/html;
index index.html index.htm;
rewrite ^/admin/(.*)$ /web/$1;
}
}
[root@mail ~]# mkdir -pv /www/html/{admin,web}
[root@mail ~]# echo "mail.bjwf125.com" > /www/html/web/index.html
[root@mail ~]# nginx -t
[root@mail ~]# service nginx reload
6、虛拟主機
[root@mail nginx]# vim /etc/nginx/nginx.conf
#注釋掉http{}段中的預定義server{}段中的所有内容;
在檔案末尾}前一行添加一條:
include conf.d/nginx-vhost.conf;
#友善後面定義,根據個人習慣而已,也可以直接在/etc/nginx/nginx.conf中配置
[root@mail nginx]# vim /etc/nginx/conf.d/nginx-vhost.conf
server {
listen 80;
server_name www.a.com;
location / {
root /www/html/a;
index index.html index.htm;
}
}
server {
listen 80;
server_name www.b.com;
location / {
root /www/html/b;
index index.html index.htm;
}
}
[root@mail nginx]# mkdir /www/html/{a,b} -pv
mkdir: created directory `/www/html/a'
mkdir: created directory `/www/html/b'
[root@mail nginx]# echo "www.a.com" > /www/html/a/index.html
[root@mail nginx]# echo "www.b.com" > /www/html/b/index.html
[root@mail nginx]# vim /etc/hosts
192.168.9.9 www.a.com
192.168.9.9 www.b.com
[root@mail nginx]# service nginx reload
[root@mail nginx]# curl http://www.a.com
www.a.com
[root@mail nginx]# curl http://www.b.com
www.b.com
###虛拟主機最簡單的方式已經配置完成,但是虛拟主機裡面還有很多參數。
7、防盜鍊
(1)、定義合規的引用
valid_referers none | blocked | server_names | string ...;
(2)、拒絕不合規的引用
if ($invalid referer) {
rewrite ^/ http://www.b.com/403.html;
}
##具體示例如下:
[root@mail conf.d]# vim nginx-vhost.conf
server {
listen 80;
server_name www.b.com;
location / {
root /www/html/b;
index index.html index.htm;
valid_referers none blocked www.b.com *.b.com;
if ($invalid_referer) {
rewrite ^/ http://www.b.com/403.html;
}
}
}
[root@mail conf.d]# vim /www/html/a/index.html
www.a.com
<img src="http://www.b.com/p_w_picpaths/1.jpg"> #在a.com中引用
[root@mail conf.d]# vim /www/html/b/index.html
www.b.com
<img src="http://www.b.com/p_w_picpaths/1.jpg"> #b.com自己引用
測試結果:
8、Nginx的反向代理
Nginx可以通過proxy子產品實作反向代理功能,在作為web反向代理伺服器時,Nginx複制接收用戶端請求,并能夠根據URL、用戶端參數或者其它的處理邏輯将使用者請求排程至上遊伺服器上(upstream server)。
Nginx在實作反向代理功能時最重要的指令為proxy_pass,它能夠将location中定義的某URI代理至指定的上遊伺服器(組)上。如下面的示例中,location的URI将被替換為上遊伺服器上的newURI。
### 例如:
[root@mail conf.d]# vim nginx-vhost.conf
server {
listen 80;
server_name www.a.com;
add_header X-Via $server_addr;
location / {
root /www/html/a;
index index.html index.htm;
}
location = /node2 {
proxy_pass http://192.168.9.11/;
}
}
##上遊伺服器必須要配置相應服務及頁面
[root@mail conf.d]# service nginx reload
[root@mail conf.d]# curl www.a.com
<img src="http://www.b.net/p_w_picpaths/1.jpg">
[root@mail conf.d]# curl http://www.a.com/node1
node1.bjwf125.com
(1)、緩存:Nginx作為反向代理時,能夠将上遊伺服器的響應緩存至本地,并在後續的用戶端請求同樣的内容時直接從本地構造響應封包。具體參數如下:
proxy_cache zone|off:定義一個用于緩存的共享記憶體區域,其可被多個地方調用;
proxy_cache_path:定義一個儲存緩存響應封包的目錄,及一個儲存緩存對象的鍵及響應中繼資料的共享記憶體區域(keys_zone=name:size),其可選參數有:
levels:每級子目錄名稱的長度,有效值為1或2,每級之間使用冒号分隔,最多為3級;
inactive:非活動緩存項從緩存中剔除之前的最大緩存時長;
max_size:緩存空間大小的上限,當需要緩存的對象超出此空間限定時,緩存管理器将基于LRU算法對其進行清理;
loader_files:緩存加載器(cache_loader)的每次工作過程使用為多少個檔案加載中繼資料;
loader_sleep:緩存加載器的每次疊代工作之後的睡眠時長;
loader_threashold:緩存加載器的最大睡眠時長;
proxy_cache_valid [ code ... ] time:用于為不同的響應設定不同時長的有效緩存時長,例如:
proxy_cache_valid 200 302 10m;
proxy_cache_methods [GET HEAD POST]:為哪些請求方法啟用緩存功能;
proxy_cache_bypass string:設定在哪種情形下,nginx将不從緩存中取資料。
示例:
# vim /etc/nginx/nginx.conf
http {
include mime.types;
default_type application/octet-stream;
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=STATIC:10m inactive=24h max_size=1g;
server {
listen 80;
server_name node1;
add_header X-Via $server_addr;
location / {
root /www/html/b;
index index.html index.htm;
proxy_pass http://192.168.9.11;
proxy_set_header Host $host;
proxy_cache STATIC;
proxy_cache_valid 200 1d;
proxy_cache_valid 301 302 10m;
proxy_cache_valid any 1m;
proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
}
}
}
[root@mail nginx]# mkdir -pv /data/nginx/cache
[root@mail nginx]# nginx -t
[root@mail nginx]# service nginx reload
緩存前請求時間
緩存後請求時間
####主要檔案太小,效果不是太明顯,有強迫症的同學可以自己測試。
##此時可以檢視緩存目錄是否有檔案生成
[root@mail ~]# ll /data/nginx/cache/
drwx------ 3 nginx nginx 4096 Jan 13 14:32 1
(2)、負載均衡:Nginx可以利用自身的upstream子產品實作,upstream子產品的負載均衡算法主要有三種,輪調(round-robin)、ip哈希(ip_hash)和最少連接配接(least_conn)三種。
upstream子產品常用的指令有:
ip_hash:基于用戶端IP位址完成請求的分發,它可以保證來自于同一個用戶端的請求始終被轉發至同一個upstream伺服器;
keepalive:每個worker程序為發送到upstream伺服器的連接配接所緩存的個數;
least_conn:最少連接配接排程算法;
server:定義一個upstream伺服器的位址,還可包括一系列可選參數,如;
weight:權重;
max_fails:最大失敗的連接配接次數,失敗連接配接的逾時時長由fail_timeout指定;
fail_timeout:等待請求的目錄伺服器發送響應的時長;
backup:用于fallback的目的,所有服務均故障時才啟動此伺服器;
down:手動标記其不再處理任何請求;
示例:
# vim /etc/nginx/nginx.conf
http {
upstream web {
server 192.168.9.11:80 max_fails=3 fail_timeout=10s;
server 192.168.9.13:80 max_fails=3 fail_timeout=10s;
server 127.0.0.1:8080 backup;
}
server {
listen 80;
server_name www.c.net;
add_header X-Via $server_addr;
location / {
root /www/html/b;
index index.html index.htm;
proxy_pass http://web;
}
}
server {
listen 8080;
server_name 127.0.0.1;
location / {
root /www/html/b;
index index.html index.htm;
}
}
[root@mail ~]# curl http://www.c.net
192.168.9.11
[root@mail ~]# curl http://www.c.net
192.168.9.13
##停掉上遊兩台伺服器後:
[root@mail ~]# curl http://www.c.net
Sorry
#####Nginx的基本功能基本完成