nginx安裝配置


nginx是一個高性能的HTTP和反向代理服務器,也是一個IMAP/POP3/SMTP代理服務器,nginx是由igor sysoev爲俄羅斯訪問量第二的Rambler.ru站點開發的。


1、nginx安裝與配置

下載地址:http://nginx.org/download/nginx-1.12.1.tar.gz

安裝準備:nginx依賴於pcre庫,需要先安裝pcre pcre-devel

yum install pcre pcre-devel -y
mkdir /root/tools
cd /root/tools
wget http://nginx.org/download/nginx-1.12.1.tar.gz
tar zxf nginx-1.12.1.tar.gz 
cd nginx-1.12.1
useradd -s /sbin/nologin nginx -M
./configure \
--user=nginx \
--group=nginx \
--prefix=/usr/local/nginx \
--with-http_ssl_module \
--with-http_stub_status_module
make && make install
echo $?
ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/nginx
cd /usr/local/nginx

[root@localhost nginx]# tree

.
├── conf   #配置文件
│   ├── fastcgi.conf
│   ├── fastcgi.conf.default
│   ├── fastcgi_params
│   ├── fastcgi_params.default
│   ├── koi-utf
│   ├── koi-win
│   ├── mime.types
│   ├── mime.types.default
│   ├── nginx.conf
│   ├── nginx.conf.default
│   ├── scgi_params
│   ├── scgi_params.default
│   ├── uwsgi_params
│   ├── uwsgi_params.default
│   └── win-utf
├── html  #網頁文件
│   ├── 50x.html
│   └── index.html
├── logs   #日誌文件
└── sbin   #主要二進制程序
    ├── nginx


1)nginx 信號控制:

TERM,INT    quick shutdown

QUIT        優雅的關閉進程,即等待請求結束後再關閉

HUP         改變配置文件,平滑的重讀配置文件

USR1        重讀日誌,在日誌按月、日分隔時使用

USR2        平滑升級

WINCH       優雅關閉進程,配合USR2來進行升級


啓動nginx:

/usr/local/nginx/sbin/nginx

重啓動nginx:

kill -QUIT `cat /usr/local/nginx/logs/nginx.pid` && /usr/local/nginx/sbin/nginx

重新加載配置文件:

kill -HUP `cat /usr/local/nginx/logs/nginx.pid` 

/usr/local/nginx/sbin/nginx -s reload

停止nginx:

kill -INT `cat /usr/local/nginx/logs/nginx.pid`

/usr/local/nginx/sbin/nginx -s stop/quit

重讀日誌文件:

kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`

/usr/local/nginx/sbin/nginx -s reopen


2)nginx配置文件:

access_log日誌格式變量說明:


$remote_addr  #遠程客戶端IP

$remote_user #客戶端用戶信息

$time_local # 本地時間

$request #請求方式,路徑和版本

$status  #響應狀態

$body_bytes_sent  #發送到客戶端的字節數

$http_referer #上一次頁面來自哪

$http_user_agent #客戶端代理信息

$http_x_forwarded_for #代理服務器轉發地址

#user  nobody;   #運行用戶
worker_processes  1; #工作進程,一般爲CPU數*核數
#全局錯誤日誌
#error_log  logs/error.log; 
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#PID文件
#pid        logs/nginx.pid;
events {
     use   epoll;  #epoll是多路複用IO(I/OMultiplexing)中的一種方式,但是僅用於linux2.6以上內核,可以大大提高nginx的性能
  #一般是配置nginx鏈接的特性,如一個worK能同時允許多個個鏈接
    worker_connections  1024; #指一個進程最大允許1024個鏈接
}
http {   #配置http服務器的主要段
    include       mime.types; #設定mime類型,類型由mime.type文件定義
    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"';
    #access_log  logs/access.log  main;
    sendfile        on; 
 #指令指定 nginx 是否調用 sendfile 函數(zero copy 方式)來輸出文件,對於普通應用,必須設爲 on,如果用來進行下載等應用磁盤IO重負載應用,可設置爲 off,以平衡磁盤與網絡I/O處理速度,降低系統的uptime.
    #tcp_nopush     on;
    #keepalive_timeout  0;
    keepalive_timeout  65;  #連接超時時間
    #gzip  on;   #開啓gzip壓縮
     #設定請求緩衝
    client_header_buffer_size    1k;
    large_client_header_buffers  4 4k;
    #設定負載均衡的服務器列表
     upstream mysvr {
    #weigth參數表示權值,權值越高被分配到的機率越大
    #本機上的Squid開啓3128端口
    server 192.168.8.1:3128 weight=5;
    server 192.168.8.2:80  weight=1;
    server 192.168.8.3:80  weight=6;
    }
    server {   #虛擬主機
        listen       80;  #偵聽80端口
        server_name  localhost; #定義使用www.xx.com訪問
        #charset koi8-r;
        #設定本虛擬主機的訪問日誌
        #access_log  logs/host.access.log  main;
        #默認請求
        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;
        }
        #反向代理
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}
        #轉發PHP動態頁面給PHP程序處理
        #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;
}

3)實際應用: 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點之間,系統負載小)


4)location 語法

location 有”定位”的意思, 根據Uri來進行不同的定位.

在虛擬主機的配置中,是必不可少的,location可以把網站的不同部分,定位到不同的處理方式上.

比如, 碰到.php, 如何調用PHP解釋器?  --這時就需要location

location 的語法

location [=|~|~*|^~] patt {

}

中括號可以不寫任何參數,此時稱爲一般匹配

也可以寫參數

因此,大類型可以分爲3種

location = patt {} [精準匹配]

location patt{}  [一般匹配]

location ~ patt{} [正則匹配]


如何發揮作用?:

首先看有沒有精準匹配,如果有,則停止匹配過程.

location = patt {
    config A
}
如果 $uri == patt,匹配成功,使用config A
   location = / {
              root   /var/www/html/;
             index  index.htm index.html;
        }
         
  location / {
             root   /usr/local/nginx/html;
            index  index.html index.htm;
  }

如果訪問  http://xxx.com/

定位流程是 

1: 精準匹配中 ”/”   ,得到index頁爲  index.htm

2: 再次訪問 /index.htm , 此次內部轉跳uri已經是”/index.htm” , 

根目錄爲/usr/local/nginx/html

3: 最終結果,訪問了 /usr/local/nginx/html/index.htm

正則也來參與.

location / {
            root   /usr/local/nginx/html;
            index  index.html index.htm;
        }
location ~ p_w_picpath {
           root /var/www/p_w_picpath;
           index index.html;
}

如果我們訪問  http://xx.com/p_w_picpath/logo.png

此時, “/” 與”/p_w_picpath/logo.png” 匹配

同時,”p_w_picpath”正則 與”p_w_picpath/logo.png”也能匹配,誰發揮作用?

正則表達式的成果將會使用.

圖片真正會訪問 /var/www/p_w_picpath/logo.png 

location / {
             root   /usr/local/nginx/html;
             index  index.html index.htm;
         }
 
location /foo {
            root /var/www/html;
             index index.html;
}

我們訪問 http://xxx.com/foo

 對於uri “/foo”,   兩個location的patt,都能匹配他們

即 ‘/’能從左前綴匹配 ‘/foo’, ‘/foo’也能左前綴匹配’/foo’,

此時, 真正訪問 /var/www/html/index.html 

原因:’/foo’匹配的更長,因此使用之.;


5)rewrite 重寫

重寫中用到的指令

if  (條件) {}  設定條件,再進行重寫 

set #設置變量

return #返回狀態碼 

break #跳出rewrite

rewrite #重寫

If  語法格式

If 空格 (條件) {

    重寫模式

}


條件又怎麼寫?

答:3種寫法

1: “=”來判斷相等, 用於字符串比較

2: “~” 用正則來匹配(此處的正則區分大小寫)

   ~* 不區分大小寫的正則

3: -f -d -e來判斷是否爲文件,爲目錄,是否存在.

例子:

            if  ($remote_addr = 192.168.1.100) {
                return 403;
            }
 if ($http_user_agent ~ MSIE) {
                rewrite ^.*$ /ie.htm;
                break; #(不break會循環重定向)
 }
             if (!-e $document_root$fastcgi_script_name) {
                rewrite ^.*$ /404.html break;
            }

注, 此處還要加break,以 xx.com/dsafsd.html這個不存在頁面爲例,我們觀察訪問日誌, 日誌中顯示的訪問路徑,依然是GET /dsafsd.html HTTP/1.1

提示: 服務器內部的rewrite和302跳轉不一樣. 跳轉的話URL都變了,變成重新http請求404.html, 而內部rewrite, 上下文沒變,就是說 fastcgi_script_name 仍然是 dsafsd.html,因此 會循環重定向.set 是設置變量用的, 可以用來達到多條件判斷時作標誌用.達到apache下的 rewrite_condition的效果

如下: 判斷IE並重寫,且不用break; 我們用set變量來達到目的

if ($http_user_agent ~* msie) {
                set $isie 1;
            }
            if ($fastcgi_script_name = ie.html) {
                set $isie 0;
            }
            if ($isie 1) {
                rewrite ^.*$ ie.html;
            }

Rewrite語法

Rewrite 正則表達式  定向後的位置 模式

Goods-3.html ---->Goods.php?goods_id=3
goods-([\d]+)\.html ---> goods.php?goods_id =$1  
location /ecshop {
index index.php;
rewrite goods-([\d]+)\.html$ /ecshop/goods.php?id=$1;
rewrite article-([\d]+)\.html$ /ecshop/article.php?id=$1;
rewrite category-(\d+)-b(\d+)\.html /ecshop/category.php?id=$1&brand=$2;
注意:用url重寫時, 正則裏如果有”{}”,正則要用雙引號包起來


6)gzip壓縮

原理:瀏覽器---請求----> 聲明可以接受 gzip壓縮 deflate壓縮 compress sdch壓縮

http協議的角度看--請求頭 聲明 acceopt-encoding: gzip deflate sdch (是指壓縮算法,其中sdchgoogle倡導的一種壓縮方式,目前支持的服務器尚不多)服務器-->迴應---把內容用gzip方式壓縮---->發給瀏覽器瀏覽<-----解碼gzip-----接收gzip壓縮內容----


gzip配置的常用參數

gzip on|off;  #是否開啓gzip

gzip_buffers 32 4K| 16 8K #緩衝(壓縮在內存中緩衝幾塊? 每塊多大?)

gzip_comp_level [1-9] #推薦6 壓縮級別(級別越高,壓的越小,越浪費CPU計算資源)

gzip_disable #正則匹配UA 什麼樣的Uri不進行gzip

gzip_min_length 200 # 開始壓縮的最小長度(再小就不要壓縮了,意義不在)

gzip_http_version 1.0|1.1 # 開始壓縮的http協議版本(可以不設置,目前幾乎全是1.1協議)

gzip_proxied          # 設置請求者代理服務器,該如何緩存內容

gzip_types text/plain application/xml # 對哪些類型的文件用壓縮 txt,xml,html ,css

gzip_vary on|off  # 是否傳輸gzip壓縮標誌


注意:圖片/mp3這樣的二進制文件,不必壓縮

因爲壓縮率比較小, 比如100->80字節,而且壓縮也是耗費CPU資源的.比較小的文件不必壓縮


7)nginx的緩存設置  提高網站性能

對於網站的圖片,尤其是新聞站, 圖片一旦發佈, 改動的可能是非常小的.我們希望能否在用戶訪問一次後, 圖片緩存在用戶的瀏覽器端,且時間比較長的緩存.

可以, 用到 nginx的expires設置 .

nginx中設置過期時間,非常簡單,在location或if段裏,來寫.

格式:expires 30s;  

      expires 30m;

      expires 2h;

      expires 30d;

(注意:服務器的日期要準確,如果服務器的日期落後於實際日期,可能導致緩存失效)

另: 304 也是一種很好的緩存手段

原理是: 服務器響應文件內容是,同時響應etag標籤(內容的簽名,內容一變,他也變), 和 last_modified_since 2個標籤值

瀏覽器下次去請求時,頭信息發送這兩個標籤, 服務器檢測文件有沒有發生變化,如無,直接頭信息返回 etag,last_modified_since

瀏覽器知道內容無改變,於是直接調用本地緩存.

這個過程,也請求了服務器,但是傳着的內容極少.

對於變化週期較短的,如靜態html,js,css,比較適於用這個方式


8)nginx反向代理服務器+負載均衡

用nginx做反向代理和負載均衡非常簡單,

支持兩個用法 1個proxy, 1個upstream,分別用來做反向代理,和負載均衡

upstream負載平衡機制:

輪詢-嚮應用服務器的請求以循環方式分發:(默認配置爲輪詢)

http {
    upstream myapp1 {
        server srv1.example.com;
        server srv2.example.com;
        server srv3.example.com;
    }

    server {
        listen 80;

        location / {
            proxy_pass http://myapp1;
        }
    }
}

最少連接 - 下一個請求被分配給具有最少數量的活動連接的服務器:

 upstream myapp1 {
        least_conn;
        server srv1.example.com;
        server srv2.example.com;
        server srv3.example.com;
    }

ip-hash - 哈希函數用於確定下一個請求應該選擇哪個服務器(基於客戶端的IP地址)。

upstream myapp1 {
    ip_hash;
    server srv1.example.com;
    server srv2.example.com;
    server srv3.example.com;
}

upstream參數說明:

weight=1  #服務器的權重,越大越高,默認爲1

max_conns=1 #限制與代理服務器同時活動鏈接的最大值,默認爲0

max_fails=1 #與服務器連接失敗的次數內將服務器變爲不可用,與fail_timeout一起使用,默認爲1

fail_timeout=10 #指定次數連接不成功內考慮服務器不可用大時間

backup #將服務器標記爲備份服務器

down  #將服務器標記爲永久不可用

以反向代理爲例, nginx不自己處理php的相關請求,而是把php的相關請求轉發給apache來處理.

反向代理後端如果有多臺服務器,自然可形成負載均衡,

但proxy_pass如何指向多臺服務器?

把多臺服務器用upstream指定綁定在一起並起個組名,然後proxy_pass指向該組:

將圖片服務器做反向代理和負載均衡:

#user  nobody;
worker_processes  1;
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#pid        logs/nginx.pid;
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"';
    #access_log  logs/access.log  main;
    sendfile        on;
    #tcp_nopush     on;
    #keepalive_timeout  0;
    keepalive_timeout  65;
    upstream imagserver{     #配置負載均衡服務器
  server 172.16.32.100:81 weight=1 max_fails=3 fail_timeout=10;
  server 172.16.32.100:82 weight=1 max_fails=3 fail_timeout=10;
}
    server {
listen81;
server_namelocalhost;
location / {
  root html;
  index index.php index.html index.htm;
  access_log logs/81_access.log main; 
}
    }
    server {
listen82;
server_namelocalhost;
location / {
  root html;
  index index.php index.html index.htm;
  access_log logs/82_access.log main;
}
    }
    server {
        listen       80;
        server_name  localhost;
    gzip  on;
    gzip_buffers 32 4k;
    gzip_comp_level 6;
    gzip_types text/plain p_w_picpath/jpeg application/xml;
    gzip_vary on;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location / {
            root   html;
            index  index.php index.html index.htm;
        }
location ~* \.(jpg|jpeg|gif|png){   #配置反向代理,將圖片請求轉發到服務器組
    proxy_set_header X-Forwarded-For $remote_addr; #將客戶端請求IP傳遞到代理服務器日誌$http_x_forwarded_for
    proxy_pass  http://imagserver;
}
        #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;
        }
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php$ {
            root           html;
            proxy_set_header X-Forwarded-For $remote_addr;
            fastcgi_pass   127.0.0.1:9000;
            include        fastcgi.conf;
        }
}

---------------------------------end-------------------------------------------------------

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章