Nginx配置文件詳細說明

1. Apache服務器和nginx的優缺點:

我們之前大量使用Apache來作爲HTTPServer。

Apache具有很優秀的性能,而且通過模塊可以提供各種豐富的功能。

1)首先Apache對客戶端的響應是支持併發的 ,運行httpd這個daemon進程之後,它會同時產生多個孩子進程/線程,每個孩子進程/線程分別對客戶端的請求進行響應;

2)另外,Apache可以提供靜態和動態的服務 ,例如對於PHP的解析不是通過性能較差的CGI實現的而是通過支持PHP的模塊來實現的(通常爲mod_php5,或者叫做apxs2)。

3)缺點:

因此通常稱爲Apache的這種Server爲process-based server ,也就是基於多進程的HTTPServer,因爲它需要對每個用戶請求創建一個孩子進程/線程進行響應;

這樣的缺點是,如果併發的請求非常多(這在大型門戶網站是很常見的)就會需要非常多的線程,從而佔用極多的系統資源CPU和內存。因此對於併發處理不是Apache的強項。

4)解決方法:

目前來說出現了另一種WebServer,在併發方面表現更加優越,叫做asynchronous servers異步服務器。最有名的爲Nginx和Lighttpd。所謂的異步服務器是事件驅動程序模式的event-driven,除了用戶的併發請求通常只需要一個單一的或者幾個線程。因此佔用系統資源就非常少。這幾種又被稱爲lightweight web server。

舉例,對於10,000的併發連接請求,nginx可能僅僅使用幾M的內存;而Apache可能需要使用幾百M的內存資源。

2. 實際中單一的使用:

1)關於單一使用Apache來作爲HTTPServer的情況我們不用再多做介紹,非常常見的應用;

上面我們介紹到Apache對於PHP等服務器端腳本的支持是通過自己的模塊來實現的,而且性能優越。

2)我們同樣可以單單使用nginx或者lighttpd來作爲HTTPServer來使用。

nginx和lighttpd和Apache類似都通過各種模塊可以對服務器的功能進行豐富的擴展,同樣都是通過conf配置文件對各種選項進行配置。

對於PHP等,nginx和lighttpd都沒有內置的模塊來對PHP進行支持,而是通過FastCGI來支持的。

Lighttpd通過模塊可以提供CGI, FastCGI和SCGI等服務,Lighttpd is capable of automatically spawning FastCGI backends as well as using externally spawned processes.

nginx則沒有自己提供處理PHP的功能,需要通過第三方的模塊來提供對PHP進行FastCGI方式的集成。


------------------------------- rewrites 所有非www.***.com的訪問 => http://www.***.com/


 server_name   web90.***.com;

 if ($host = "web90.***.com") {

                rewrite ^(.*)$ http://www.test.com$1 permanent;

        }


---------------------------------nginx 停止/平滑重啓#p#分頁標題#e#


nginx的信號控制


TERM,INT 快速關閉

QUIT  從容關閉

HUP   平滑重啓,重新加載配置文件

USR1  重新打開日誌文件,在切割日誌時用途比較大

USR2  平滑升級可執行程序

WINCH 從容關閉工作進程


1) 從容停止:


kill -QUIT Nginx主進程號


kill -QUIT '/usr/local/webserver/nginx/logs/nginx.pid'

 


2)快速停止:


kill -TERM Nginx主進程號


kill -TERM '/usr/local/webserver/nginx/logs/nginx.pid'


kill -INTN ginx主進程號


kill -INT  '/usr/local/webserver/nginx/logs/nginx.pid'



3)強制停止所有nginx進程


pkill -9 nginx


1)平滑重啓


kill -HUP nginx主進程號


kill -HUP '/usr/local/webserver/nginx/logs/nginx.pid'


-----------------------------nginx.conf

#p#分頁標題#e#

 


worker_processes 8;


指定工作衍生進程數


一般等於cpu的總核數或總核數的兩倍,例如兩個四核的cpu,總核數爲8



events

{

  use epoll; //使用的網絡i/o模型,linux系統推薦epoll,freebsd推薦kqueue

  worker_connections 65535; //允許的鏈接數

}


location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { access_log off;關閉日誌 expires 30d;//通過expires指令輸出Header頭來實現本地緩存,30天 } location ~ .*\.(js|css)$ { access_log off;關閉日誌 expires 1h; } =====================每




{


access_log off;關閉日誌


expires 30d;//通過expires指令輸出Header頭來實現本地緩存,30天


}


location ~ .*\.(js|css)$


{


access_log off;關閉日誌


expires 1h;


}


=====================每天定時切割nginx日誌腳本


vim /usr/local/webserver/nginx/sbin/cut_nginx_log.sh

#!/bin/bash

# This script run at 00:00


# The Nginx logs path

logs_path="/usr/local/webserver/nginx/logs/";


mkdir -p ${logs_path}$(date -d "yesterday" + "%Y")/$(date -d "yesterday" + "%m")/#p#分頁標題#e#

mv ${logs_path}access.log ${logs_path}$(date -d "yesterday" + "%Y")/$(date -d "yesterday" + "%m")/access_$(date -d "yesterday" + "%Y%m%d").log

kill -USR1 'cat /usr/local/webserver/nginx/nginx.pid'


chown -R www:www cut_nginx_log.sh

chmod +x cut_nginx_log.sh


crontab -e

00 * * * /bin/bash /usr/local/webserver/nginx/sbin/cut_nginx_log.sh


#/sbin/service crond restart


--------------nginx 配置 gzip壓縮


一般情況下壓縮後的html、css、js、php、jhtml等文件,大小能降至原來的25%,也就是說,原本一個100k的html,壓縮後只剩下25k。這無疑能節省很多帶寬,也能降低服務器的負載。

在nginx中配置gzip比較簡單


一般情況下只要在nginx.conf的http段中加入下面幾行配置即可


引用

   gzip  on;

   gzip_min_length  1000;

   gzip_buffers     4 8k;

   gzip_types       text/plain application/x-javascript text/css text/html application/xml;


重啓nginx

可以通過網頁gzip檢測工具來檢測網頁是否啓用了gzip

http://gzip.zzbaike.com/


---------------重定向nginx錯誤頁面的方法


error_page 404  /404.html;


這個404.html保證在nginx主目錄下的html目錄中即可,如果需要在出現404錯誤後直接跳轉到另外一個地址,可以直接設置如下:



error_page 404 http://www.***.net ;



同樣的方式可以定義常見的403、500等錯誤。#p#分頁標題#e#



特別注意的是404.html文件頁面大小要超過512k,不然會被ie瀏覽器替換爲ie默認的錯誤頁面。


 


 


------------------------------虛擬主機配置


server {

    listen   80;

    server_name  localhost;

    access_log  /var/log/nginx/localhost.access.log;


    location / {

        root   /var/www/nginx-default;

        index index.php index.html index.htm;

    }


    location /doc {

        root   /usr/share;

        autoindex on;

        allow 127.0.0.1;

        deny all;

    }


    location /images {

        root   /usr/share;

        autoindex on;

    }

    location ~ \.php$ {

        fastcgi_pass   127.0.0.1:9000;

        fastcgi_index  index.php;

        fastcgi_param  SCRIPT_FILENAME  /var/www/nginx-default$fastcgi_script_name;

        include /etc/nginx/fastcgi_params;

    }

}



server {

    listen   80;

    server_name  sdsssdf.localhost.com;

    access_log  /var/log/nginx/localhost.access.log;


    location / {

        root   /var/www/nginx-default/console;

        index index.php index.html index.htm; } location /doc { root /usr/share; autoindex on; allow 127.0.0.1; deny all; } location /images { root /usr/share; autoindex on; } location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.p

#p#分頁標題#e#


    }


    location /doc {

        root   /usr/share;

        autoindex on;

        allow 127.0.0.1;

        deny all;

    }


    location /images {

        root   /usr/share;

        autoindex on;

    }

    location ~ \.php$ {

        fastcgi_pass   127.0.0.1:9000;

        fastcgi_index  index.php;

        fastcgi_param  SCRIPT_FILENAME  /var/www/nginx-default$fastcgi_script_name;

        include /etc/nginx/fastcgi_params;

    }

}



----------------------監控  


location ~ ^/NginxStatus/ {


stub_status on; #Nginx 狀態監控配置     

}


這樣通過 http://localhost/NginxStatus/(最後的/不能掉) 監控到 Nginx 的運行信息:


Active connections: 1

server accepts handled requests

1 5

Reading: 0 Writing: 1 Waiting: 0


NginxStatus 顯示的內容意思如下:#p#分頁標題#e#


    active connections – 當前 Nginx 正處理的活動連接數。

    server accepts handled requests -- 總共處理了 14553819 個連接 , 成功創建 14553819 次握手 ( 證明中間沒有失敗的 ), 總共處理了 19239266 個請求 ( 平均每次握手處理了 1.3 個數據請求 )。

    reading -- nginx 讀取到客戶端的 Header 信息數。

    writing -- nginx 返回給客戶端的 Header 信息數。

    waiting -- 開啓 keep-alive 的情況下,這個值等於 active - (reading + writing),意思就是 Nginx 已經處理完正在等候下一次請求指令的駐留連接。


 


-------------------------------靜態文件處理


通過正則表達式,我們可讓 Nginx 識別出各種靜態文件


 


location ~ \.(htm|html|gif|jpg|jpeg|png|bmp|ico|css|js|txt)$ {


        root /var/www/nginx-default/html;

        access_log off;

        expires 24h;

        }


對於例如圖片、靜態 HTML 文件、js 腳本文件和 css 樣式文件等,我們希望 Nginx 直接處理並返回給瀏覽器,這樣可以大大的加快網頁瀏覽時的速度。因此對於這類文件我們需要通過 root 指令來指定文件的存放路徑 ,同時因爲這類文件並不常修改,通過 expires 指令來控制其在瀏覽器的緩存,以減少不必要的請求。 expires 指令可以控制 HTTP 應答中的“ Expires ”和“ Cache-Control ”的頭標(起到控制頁面緩存的作用)。您可以使用例如以下的格式來書寫 Expires:


expires 1 January, 1970, 00:00:01 GMT;

expires 60s;

expires 30m;

expires 24h;

expires 1d;

expires max;

expires off;


這樣當你輸入http://192.168.200.100/1.html的時候會自動跳轉到var/www/nginx-default/html/1.html


例如 images 路徑下的所有請求可以寫爲:


 #p#分頁標題#e#


location ~ ^/images/ {

    root /opt/webapp/images;

}


------------------------動態頁面請求處理[集羣]


Nginx 本身並不支持現在流行的 JSP、ASP、PHP、PERL 等動態頁面,但是它可以通過反向代理將請求發送到後端的服務器,例如 Tomcat、Apache、IIS 等來完成動態頁面的請求處理。前面的配置示例中,我們首先定義了由 Nginx 直接處理的一些靜態文件請求後,其他所有的請求通過 proxy_pass 指令傳送給後端的服務器 (在上述例子中是 Tomcat)。最簡單的 proxy_pass 用法如下:


location / { proxy_pass http://localhost:8080; proxy_set_header X-Real-IP $remote_addr; } 這裏我們沒有使用到集羣,而是將請求直接送到運行在 8080 端口的 Tomcat 服務上來完成類似 JSP


   proxy_pass        http://localhost:8080;

    proxy_set_header  X-Real-IP  $remote_addr;

}


這裏我們沒有使用到集羣,而是將請求直接送到運行在 8080 端口的 Tomcat 服務上來完成類似 JSP 和 Servlet 的請求處理。


當頁面的訪問量非常大的時候,往往需要多個應用服務器來共同承擔動態頁面的執行操作,這時我們就需要使用集羣的架構。 Nginx 通過 upstream 指令來定義一個服務器的集羣,最前面那個完整的例子中我們定義了一個名爲 tomcats 的集羣,這個集羣中包括了三臺服務器共 6 個 Tomcat 服務。而 proxy_pass 指令的寫法變成了:


# 集羣中的所有後臺服務器的配置信息

    upstream tomcats {

     server 192.168.0.11:8080 weight=10;

     server 192.168.0.11:8081 weight=10;

     server 192.168.0.12:8080 weight=10;

     server 192.168.0.12:8081 weight=10;

     server 192.168.0.13:8080 weight=10;

     server 192.168.0.13:8081 weight=10;#p#分頁標題#e#

    }

    location / {

        proxy_pass http://tomcats;# 反向代理

        include proxy.conf;

        }


----------------------壓力測試


wget http://blog.s135.com/soft/linux/webbench/webbench-1.5.tar.gz  

tar zxvf webbench-1.5.tar.gz  

cd webbench-1.5  

make && make install


#webbench -c 100 -t 10 http://192.168.200.100/info.php


參數說明:-c表示併發數,-t表示持續時間(秒)


root@ubuntu-desktop:/etc/nginx/sites-available# webbench -c 100 -t 10 http://192.168.200.100/info.php

Webbench - Simple Web Benchmark 1.5

Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.


Benchmarking: GET http://192.168.200.100/info.php

clients, running 10 sec.


Speed=19032 pages/min, 18074373 bytes/sec.

Requests: 3172 susceed, 0 failed.


-------------------------------PPC提供nginx詳細配置說明


#運行用戶

user  nobody nobody;

#啓動進程

worker_processes  2;#p#分頁標題#e#

#全局錯誤日誌及PID文件

error_log  logs/error.log notice;

pid        logs/nginx.pid;

#工作模式及連接數上限

events{use epoll;

worker_connections      1024;}#設定http服務器,利用它的反向代理功能提供負載均衡支持



http{#設定mime類型

            include      conf/mime.types;

            default_type  application/octet-stream;

            #設定日誌格式

            log_format main'$remote_addr - $remote_user [$time_local] ''"$request" $status $bytes_sent ''"$http_referer" "$http_user_agent" ''"$gzip_ratio"';

            log_format download'$remote_addr - $remote_user [$time_local] ''"$request" $status $bytes_sent ''"$http_referer" "$http_user_agent" ''"$http_range" "$sent_http_content_range"';

            #設定請求緩衝

            client_header_buffer_size    1k;

            large_client_header_buffers  4 4k;

           

            #開啓gzip模塊

            gzip on;

            gzip_min_length  1100; 


            gzip_buffers    4 8k;

            gzip_types      text/plain;

            output_buffers  1 32k;

            postpone_output  1460;

           

            #設定access log

            access_log  logs/access.log  main;

            client_header_timeout  3m;

            client_body_timeout    3m;

            send_timeout          3m;

            sendfile                on;

            tcp_nopush              on;

            tcp_nodelay            on;

            keepalive_timeout  65;

           

            #設定負載均衡的服務器列表

            upstream mysvr{#weigth參數表示權值,權值越高被分配到的機率越大

                        #本機上的Squid開啓3128端口#p#分頁標題#e#

                        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;

                        server_name    192.168.8.1 www.okpython.com;

                        charset gb2312;

                        #設定本虛擬主機的訪問日誌

                        access_log  logs/www.yejr.com.access.log  main;

                        #如果訪問 /img/*, /js/*, /css/* 資源,則直接取本地文件,不通過squid

                        #如果這些文件較多,不推薦這種方式,因爲通過squid的緩存效果更好

                        location ~ ^/(img|js|css)/  {

                                    root    /data3/Html;

                                    expires 24h;

                        } #對 / 啓用負載均衡 location / { proxy_pass http://mysvr; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_



                        #對 "/" 啓用負載均衡

                        location / {

                                    proxy_pass      http://mysvr;

                                    proxy_redirect          off;

                                    proxy_set_header        Host $host;

                                    proxy_set_header        X-Real-IP $remote_addr;

                                    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;

                                    client_max_body_size    10m;

                                    client_body_buffer_size 128k;

                                    proxy_connect_timeout  90;#p#分頁標題#e#

                                    proxy_send_timeout      90;

                                    proxy_read_timeout      90;

                                    proxy_buffer_size      4k;

                                    proxy_buffers          4 32k;

                                    proxy_busy_buffers_size 64k;

                                    proxy_temp_file_write_size 64k;

                        }

                        #設定查看Nginx狀態的地址

                        location /NginxStatus {

                                    stub_status            on;

                                    access_log              on; 



                                    auth_basic              "NginxStatus";

                                    auth_basic_user_file  conf/htpasswd;   #conf/htpasswd 文件的內容用 apache 提供的 htpasswd 工具來產生即可

                  }

      }

}


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