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 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 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
100 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 工具來產生即可
                  }
      }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM