1. 程式人生 > >NGINX配置以及優化

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方式的整合。

===============Nginx配置檔案nginx.conf中文詳解

#定義Nginx執行的使用者和使用者組
user www www;

#nginx程序數,建議設定為等於CPU總核心數。
worker_processes 8;

#全域性錯誤日誌定義型別,[ debug | info | notice | warn | error | crit ]
error_log /var/log/nginx/error.log info;

#程序檔案
pid /var/run/nginx.pid;

#一個nginx程序開啟的最多檔案描述符數目,理論值應該是最多開啟檔案數(系統的值ulimit -n)與nginx程序數相除,但是nginx分配請求並不均勻,所以建議與ulimit -n的值保持一致。
worker_rlimit_nofile 65535;

#工作模式與連線數上限
events
{
#參考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型是Linux 2.6以上版本核心中的高效能網路I/O模型,如果跑在FreeBSD上面,就用kqueue模型。
use epoll;
#單個程序最大連線數(最大連線數=連線數*程序數)
worker_connections 65535;
}

#設定http伺服器
http
{
include mime.types; #副檔名與檔案型別對映表
default_type application/octet-stream; #預設檔案型別
#charset utf-8; #預設編碼
server_names_hash_bucket_size 128; #伺服器名字的hash表大小
client_header_buffer_size 32k; #上傳檔案大小限制
large_client_header_buffers 4 64k; #設定請求緩
client_max_body_size 8m; #設定請求緩
sendfile on; #開啟高效檔案傳輸模式,sendfile指令指定nginx是否呼叫sendfile函式來輸出檔案,對於普通應用設為 on,如果用來進行下載等應用磁碟IO重負載應用,可設定為off,以平衡磁碟與網路I/O處理速度,降低系統的負載。注意:如果圖片顯示不正常把這個改成off。
autoindex on; #開啟目錄列表訪問,合適下載伺服器,預設關閉。
tcp_nopush on; #防止網路阻塞
tcp_nodelay on; #防止網路阻塞
keepalive_timeout 120; #長連線超時時間,單位是秒

#FastCGI 相關引數是為了改善網站的效能:減少資源佔用,提高訪問速度。下面引數看字面意思都能理解。
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;

#gzip模組設定
gzip on; #開啟gzip壓縮輸出
gzip_min_length 1k; #最小壓縮檔案大小
gzip_buffers 4 16k; #壓縮緩衝區
gzip_http_version 1.0; #壓縮版本(預設1.1,前端如果是squid2.5請使用1.0)
gzip_comp_level 2; #壓縮等級
gzip_types text/plain application/x-javascript text/css application/xml;
#壓縮型別,預設就已經包含text/html,所以下面就不用再寫了,寫上去也不會有問題,但是會有一個warn。
gzip_vary on;
#limit_zone crawler $binary_remote_addr 10m; #開啟限制IP連線數的時候需要使用

upstream blog.ha97.com {
#upstream的負載均衡,weight是權重,可以根據機器配置定義權重。weigth引數表示權值,權值越高被分配到的機率越大。
server 192.168.80.121:80 weight=3;
server 192.168.80.122:80 weight=2;
server 192.168.80.123:80 weight=3;
}

#虛擬主機的配置
server
{
#監聽埠
listen 80;
#域名可以有多個,用空格隔開
server_name www.ha97.com ha97.com;
index index.html index.htm index.php;
root /data/www/ha97;
location ~ .*.(php|php5)?$
{
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
#圖片快取時間設定
location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 10d;
}
#JS和CSS快取時間設定
location ~ .*.(js|css)?$
{
expires 1h;
}
#日誌格式設定
log_format access '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $http_x_forwarded_for';
#定義本虛擬主機的訪問日誌
access_log /var/log/nginx/ha97access.log access;

#對 "/" 啟用反向代理
location / {
proxy_pass http://127.0.0.1:88;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
#後端的Web伺服器可以通過X-Forwarded-For獲取使用者真實IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#以下是一些反向代理的配置,可選。
proxy_set_header Host $host;
client_max_body_size 10m; #允許客戶端請求的最大單檔案位元組數
client_body_buffer_size 128k; #緩衝區代理緩衝使用者端請求的最大位元組數,
proxy_connect_timeout 90; #nginx跟後端伺服器連線超時時間(代理連線超時)
proxy_send_timeout 90; #後端伺服器資料回傳時間(代理髮送超時)
proxy_read_timeout 90; #連線成功後,後端伺服器響應時間(代理接收超時)
proxy_buffer_size 4k; #設定代理伺服器(nginx)儲存使用者頭資訊的緩衝區大小
proxy_buffers 4 32k; #proxy_buffers緩衝區,網頁平均在32k以下的設定
proxy_busy_buffers_size 64k; #高負荷下緩衝大小(proxy_buffers*2)
proxy_temp_file_write_size 64k;
#設定快取資料夾大小,大於這個值,將從upstream伺服器傳
}

#設定檢視Nginx狀態的地址
location /NginxStatus {
stub_status on;
access_log on;
auth_basic "NginxStatus";
auth_basic_user_file conf/htpasswd;
#htpasswd檔案的內容可以用apache 提供的htpasswd工具來產生。
}

#本地動靜分離反向代理配置
#所有jsp的頁面均交由tomcatresin 處理
location ~ .(jsp|jspx|do)?$ {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
#所有靜態檔案由nginx直接讀取不經過tomcat或resin
location ~ .*.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$
{ expires 15d; }
location ~ .*.(js|css)?$
{ expires 1h; }
}
}

=================

每個nginx程序消耗的記憶體10兆的模樣

檢視當前的PHP FastCGI程序數是否夠用:
netstat -anpo | grep "php-cgi" | wc -l
  如果實際使用的“FastCGI程序數”接近預設的“FastCGI程序數”,那麼,說明“FastCGI程序數”不夠用,需要增大。

------------------------------ error_log 日誌分為

nginx的log有以下幾種型別: [ debug | info | notice | warn | error | crit ]
在nginx.conf的設定:error_log logs/error.log debug;
debug 為最詳細 crit最少

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

server_name web90.***.com;

if ($host = "web90.***.com") {
rewrite ^(.*)$ http://www.test.com$1 permanent;
}

---------------------------------nginx 停止/平滑重啟

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'


---------------------------- Location語法

location [=|~|~*|^~] /uri/ { … }

= 開頭表示精確匹配
^~ 開頭表示uri以某個常規字串開頭,理解為匹配 url路徑即可
~ 為區分大小寫匹配
~* 為不區分大小寫匹配
!~和!~*分別為區分大小寫不匹配及不區分大小寫不匹配
/ 通用匹配,任何請求都會匹配到。
多個location配置的情況下匹配順序為
首先匹配 =,其次匹配^~, 其次是按檔案中順序的正則匹配,最後是交給 / 通用匹配。當有匹配成功時候,停止匹配,按當前匹配規則處理請求。
處理靜態檔案請求,這是nginx作為http伺服器的強項
# 有兩種配置模式,目錄匹配或字尾匹配,任選其一或搭配使用
location ^~ /static/ {
root /webroot/static/;
}
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
root /webroot/res/;
}

---------------------------- ReWrite語法
last – 基本上都用這個Flag。
break – 中止Rewirte,不在繼續匹配
redirect – 返回臨時重定向的HTTP狀態302
permanent – 返回永久重定向的HTTP狀態301

----------------------------開啟記錄nginx access log中post請求

vim /usr/local/nginx/conf/vhost/ssc.conf

log_format access '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent$request_body "$http_referer" "$
http_user_agent" $http_x_forwarded_for';
access_log logs/ssc.log access ;

------------------------------ 關閉 access log

server
{
access_log /dev/null;

}

  這樣全部把他們丟到系統的黑洞裡了。不用每時每刻都往系統磁碟瘋狂的讀寫日誌了 還延長硬碟的壽命。
  完全重啟Nginx

-----------------------------php-fpm

php.ini中memory_limit設低了會出錯,修改了php.ini的memory_limit為128M,重啟nginx,發現好了,原來是PHP的記憶體不足了。

php-fpm 來管理FastCGI,可以修改配置檔案中的以下值:

在PHP5.3.X中的php-fpm,配置檔案 php-fpm.conf 對於程序管理有兩種方法,一種是靜態(static),一種是動態(dynamic)。
如果設定成 static,程序數始終都是 pm.max_children 指定的數量。
如果設定成 dynamic,則程序數是動態的,最開始是 pm.start_servers 指定的數量,如果請求較多,則會自動增加,保證空閒的程序數不小於pm.min_spare_servers,如果程序數較多,也會進行相應清理,保證程序數不多於 pm.max_spare_servers。
當php-fpm啟動後,一個php-fpm程序處理過一些請求後,有些記憶體是釋放不掉的,佔用的記憶體將達到20M-30M不等。
對於記憶體大的伺服器(比如說4G)來說,指定靜態的 max_children 後就不需要再進行額外的程序數目控制。比如我們指定為100個,那麼php-fpm耗費的記憶體就能控制在大概2G,剩餘的2G記憶體可以處理別的任務。
如果記憶體小(比如1G),那麼指定靜態的程序數量,可以保證php-fpm只獲取夠用的記憶體,將不多的記憶體分配給其他應用去使用,有利於伺服器的穩定,執行暢通。



<value name="max_children">128</value>

同時處理的併發請求數,即它將開啟最多128個子執行緒來處理併發連線。

<value name="rlimit_files">102400 </value>

最多開啟檔案數。

<value name="max_requests">204800 </value>

每個程序在重置之前能夠執行的最多請求數。


<value name="log_level">notice</value>
<value name="process_control_timeout">5s</value>
<value name="display_errors">1</value>
<value name="style">static</value>
<value name="StartServers">20</value>
Sets the desired minimum number of idle server processes.
Used only when 'apache-like' pm_style is selected
<value name="MinSpareServers">5</value>
Sets the desired maximum number of idle server processes.
Used only when 'apache-like' pm_style is selected
<value name="MaxSpareServers">35</value>

<value name=”request_terminate_timeout”>30s</value> fast-cgi的執行指令碼時間
<value name="request_terminate_timeout">0s</value>
The timeout (in seconds) for serving of single request after which a php backtrace will be dumped to slow.log file'0s' means 'off'
<value name="request_slowlog_timeout">2s</value>
The log file for slow requests
<value name="slowlog">/data/logs/php/php-fpm-slow.log</value>

-----------------------------fastcgi.conf


fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;

fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SERVER_PROTOCOL $server_protocol;

fastcgi_param GATEWAY_INTERFACE CGI/1.1;
fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;

fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;
fastcgi_param SERVER_ADDR $server_addr;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param REDIRECT_STATUS 200;

=============================== nginx標識

http://www.php100.com/html/webkaifa/apache/2011/0520/8098.html

以下為字串匹配操作符

~ 為區分大小寫匹配
~* 為不區分大小寫匹配
!~和!~*分別為區分大小寫不匹配及不區分大小寫不匹配



檔案和目錄判斷

  -f和!-f判斷是否存在檔案

  -d和!-d判斷是否存在目錄

  -e和!-e判斷是否存在檔案或目錄

  -x和!-x判斷檔案是否可執行

flag標記有:

  * last 相當於Apache裡的[L]標記,表示完成rewrite

  * break 終止匹配, 不再匹配後面的規則

  * redirect 返回302臨時重定向 位址列會顯示跳轉後的地址

  * permanent 返回301永久重定向 位址列會顯示跳轉後的地址

  一些可用的全域性變數有,可以用做條件判斷(待補全)

  $args

  $content_length

  $content_type

  $document_root

  $document_uri

  $host

  $http_user_agent

  $http_cookie

  $limit_rate

  $request_body_file

  $request_method

  $remote_addr

  $remote_port

  $remote_user

  $request_filename

  $request_uri

  $query_string

  $scheme

  $server_protocol

  $server_addr

  $server_name

  $server_port

  $uri

$http_referer

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

檢視物理cpu顆數
cat /proc/cpuinfo | grep physical | uniq -c
8 physical id : 1
(說明實際上是1顆8核的CPU)

在伺服器上執行top,然後按1,就可以看到CPU核心的工作情況。如果多個CPU核心的利用率都相差不多,證明nginx己經成功的利用了多核CPU。

worker_processes 8;

指定工作衍生程序數 ,一般等於cpu的總核數或總核數的兩倍,例如兩個四核的cpu,總核數為8


events
{
use epoll; //使用的網路i/o模型,linux系統推薦epoll,freebsd推薦kqueue
worker_connections 65535; //允許的連結數
}

#max_clients = worker_processes * worker_connections

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$

{

access_log off;關閉日誌

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

}

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

{

access_log off;關閉日誌

expires 1h;

}

====================== 重寫

if (!-e $request_filename ) {
rewrite "/test/(.*[^js|css|jpg|gif|html])$" /index.php?r=test/$1 last;

rewrite "(.*)([a|c|f])$" /static/login/$1$2/login.html last;
rewrite "(.*)([a|c|f])/$" /static/login/$1$2/login.html last;
rewrite "(.*)([a|c])/account/login.html$" /static/login/$1$2/login.html last;
rewrite "(.*)f/user/login.html$" /static/login/$1f/login.html last;
rewrite "(.*)([a|c|f]{1})_[0-9]+/multiple/redirection?(.*)$" /index.php?r=multiple/redirection&shortFlag=$2&$3 last;
rewrite "(.*)([a|c|f]{1})_[0-9]+/multiple/(.*)$" /index.php?r=multiple/$3&shortFlag=$2 last;
rewrite "(.*[a|c])_[0-9]+/index.htm$" /index.php?co=$1&r=backend last;
rewrite "(.*[a|c])/(.*[^html])$" /index.php?co=$1&r=backend/$2 last;
rewrite "(.*[a|c])_[0-9]+/(.*[^html])$" /index.php?co=$1&r=backend/$2 last;

rewrite "(.*f)_[0-9]+/index.htm$" /index.php?co=$1&r=frontend last;
rewrite "(.*f)/(.*)$" /index.php?co=$1&r=frontend/$2 last;
rewrite "(.*f)_[0-9]+/(.*)$" /index.php?co=$1&r=frontend/$2 last;

rewrite "site/(.*)$" /index.php?&r=site/$1 last;
}

================nginx 日誌格式

推薦:

log_format access '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $http_x_forwarded_for';


218.28.60.30 - - [20/May/2011:15:02:12 +0800] "GET /manager/html HTTP/1.1" 404 168 "-" "Mozilla/3.0 (compatible; Indy Library)" -

log_format access2 '[$time_local] $remote_addr $status $request_time $body_bytes_sent "$request" "$http_referer"';

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"';

=====================每天定時切割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")/
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

=============================== conf 配置標頭檔案

user www www;

worker_processes 1;

error_log /usr/local/nginx/logs/nginx_error.log crit;

pid /usr/local/nginx/logs/nginx.pid;

#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 51200;

events
{
use epoll;
worker_connections 51200;
}

=================================== http核心模組

user www www;

worker_processes 8;

error_log /data/logs/nginx/nginx_error.log crit;

pid /usr/local/webserver/nginx/nginx.pid;

#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 65535;

events
{
use epoll;
worker_connections 65535;
}

http
{
include mime.types;
default_type application/octet-stream;

charset utf-8;

server_names_hash_bucket_size 128;
client_header_buffer_size 128k;
large_client_header_buffers 4 128k;
client_max_body_size 8m; #指令指定允許客戶端連線的最大請求實體大小,它出現在請求頭部的Content-Length欄位。

sendfile on;
tcp_nopush on;

keepalive_timeout 60; #引數的第一個值指定了客戶端與伺服器長連線的超時時間,超過這個時間,伺服器將關閉連線。

tcp_nodelay on;

fastcgi_connect_timeout 60;
fastcgi_send_timeout 60;
fastcgi_read_timeout 60;
fastcgi_buffer_size 256k;
fastcgi_buffers 8 256k;
fastcgi_busy_buffers_size 256k;
fastcgi_temp_file_write_size 256k;

fastcgi_intercept_errors on;

語法:fastcgi_intercept_errors on|off
預設值:fastcgi_intercept_errors off
使用欄位:http, server, location
這個指令指定是否傳遞4xx和5xx錯誤資訊到客戶端,或者允許nginx使用error_page處理錯誤資訊。
你必須明確的在error_page中指定處理方法使這個引數有效,正如Igor所說“如果沒有適當的處理方法,nginx不會攔截一個錯誤,這個錯誤不會顯示自己的預設頁面,這裡允許通過某些方法攔截錯誤。


gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.0;
gzip_comp_level 2;
gzip_types text/plain application/x-javascript text/css application/xml;
gzip_vary on;

#limit_zone crawler $binary_remote_addr 10m;

log_format access '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $http_x_forwarded_for';

#upstream member {
# server 192.168.1.203:80;
# }

#include vhost/*.conf;

----------------- server核心模組

server
{
listen 80;
server_name www.***.com ;
index index.html index.htm index.php;
root /data/www/***/webroot;
location / {
index index.php index.html index.htm;
if (-f $request_filename) {
break;
}
if (-d $request_filename) {
break;
}
rewrite ^(.+)$ /index.php?q=$1 last;

}

location / {
return 404;
}

location ~ .*\.(php|php5)?$
{
#fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fcgi.conf;
# rewrite ^(.+)$ index.php?q=$1 last;
}


location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
access_log off;
expires 30d;
}
location ~ .*\.(js|css)$
{
access_log off;
expires 30d;
}
#access_log /data/logs/nginx/binhaixian.access.log access;

}

----------------FastCGI模組

fastcgi_connect_timeout 60;#預設值為60.指定同FastCGI伺服器的連線超時時間,這個值不能超過75秒

fastcgi_send_timeout 300;#指令為上游伺服器設定等待一個FastCGI程序的傳送資料時間,如果有一些直到它們執行完才有輸出的長時間執行的FastCGI程序,那麼可以修改這個值,如果你在上游伺服器的error log裡面發現一些超時錯誤,那麼可以恰當的增加這個值。指令指定請求伺服器的超時時間,指完成了2次握手的連線,而不是完整的連線 ,如果在這期間客戶端沒有進行資料傳遞,那麼伺服器將關閉這個連線。
fastcgi_read_timeout 300;#預設值為60.前端FastCGI伺服器的響應超時時間,如果有一些直到它們執行完才有輸出的長時間執行的FastCGI程序,或者在錯誤日誌中出現前端伺服器響應超時錯誤,可能需要調整這個值
fastcgi_buffer_size 64k; #這個引數指定將用多大的緩衝區來讀取從FastCGI程序到來應答頭。預設的緩衝區大小為fastcgi_buffers指令中的每塊大小 ,可以將這個值設定更小。

fastcgi_buffers 4 64k; #這個引數指定了從FastCGI程序到來的應答,本地將用多少和多大的緩衝區讀取。
預設這個引數等於分頁大小 ,根據環境的不同可能是4K, 8K或16K。

#getconf PAGESIZE 得到分頁大小,返回的單位為bytes
4096
例如fastcgi_buffers 256 4k; # 設定緩衝區大小為4k + 256 * 4k = 1028k。這意味著所有FastCGI返回的應答,nginx將超過1M的部分寫入磁碟,1M以內的部分寫入記憶體。

fastcgi_busy_buffers_size 128k;

fastcgi_temp_file_write_size 128k;

fastcgi_pass 127.0.0.1:9000; #指定FastCGI伺服器監聽埠與地址,可以是本機或者其它
fastcgi_index index.php;
include fcgi.conf;

------------------------------------------ location設定優先順序

(location =) > (location 完整路徑 >) >(location ^~ 路徑) >(location ~* 正則) >(location 路徑)
只要匹配到,其它的都會忽略,然後返回到改匹配。


如果都是正則,都能夠匹配,以配置檔案出現順序來,誰在前誰優先。

------------------------------------------ 一個error對應一個slow log

#php-fpm.log

May 27 11:50:44. 120263 [ERROR ] fpm_trace_get_long(), line 78: ptrace(PEEKDATA) failed: Input/output error (5)

#php-fpm-slow.log
May 27 11:50:44.
120041 pid 25314 (pool default)
script_filename = /data/www/***/webroot/index.php
[0xbf923f60] closedir() /data/www/cakephp/cake/libs/folder.php:191
[0xbf9241b0] read() /data/www/cakephp/cake/libs/folder.php:465
[0xbf924610] __tree() /data/www/cakephp/cake/libs/folder.php:441
[0xbf924c80] tree() /data/www/cakephp/cake/libs/configure.php:1029
[0xbf9259e0] __find(
) /data/www/cakephp/cake/libs/configure.php:954
[0xbf925b60] import() /data/www/***/config/bootstrap.php:52
[0xbf9263a0] +++ dump failed

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

一般情況下壓縮後的html、css、js、php、jhtml等檔案,大小能降至原來的25%,也就是說,原本一個100k的html,壓縮後只剩下25k。這無疑能節省很多頻寬,也能降低伺服器的負載。
在nginx中配置gzip比較簡單

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

引用
gzip on;
gzip_min_length 1024;#
設定被壓縮的最小請求,單位為bytes。少於這個值大小的請求將不會被壓縮,這個值由請求頭中的Content-Length欄位決定。建議值為1k;

gzip_buffers 4 8k; #指定快取壓縮應答的緩衝區數量和大小,如果不設定,一個快取區的大小為分頁大小,根據環境的不同可能是4k或8k。以8k為單位,按照原始資料大小以8k為單位的4倍申請記憶體。

gzip_http_version 1.0;
gzip_types text/plain application/x-javascript text/css text/html application/xml;#為除“text/html”之外的MIME型別啟用壓縮,“text/html”總是會被壓縮

gzip_comp_level 2;#指定壓縮等級,其值從1到9,1為最小化壓縮(處理速度快),9為最大化壓縮(處理速度慢)。
gzip_vary on;#啟用應答頭“Vary: Accept-Encoding”,注意,由於一個bug將導致IE 4-6無法快取內容。

重啟nginx
可以通過網頁gzip檢測工具來檢測網頁是否啟用了gzip
http://gzip.zzbaike.com/

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


error_page 404 /404.html;
error_page 403 /error.html;


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


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


同樣的方式可以定義常見的403、500等錯誤。


特別注意的是404.html檔案頁面大小要超過512k,不然會被ie瀏覽器替換為ie預設的錯誤頁面。

#502 等錯誤可以用同樣的方法來配置。
error_page 500 502 503 504 = /50x.html;

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

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.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 顯示的內容意思如下:

  • 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;
}

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)?$
{
#root /var/www/ttt/www/static/cache/;
access_log off;
expires 30d;
}

location ~ .*\.(js|css|html)?$
{
#root /var/www/ttt/www/static/cache/;
access_log off;
expires 7d;
}

對於例如圖片、靜態 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 路徑下的所有請求可以寫為:

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 和 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;
}
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表示持續時間(秒)

[email protected]:/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;
#全域性錯誤日誌及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埠
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_forwarded_for;
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 90;
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 工具來產生即可
}
}
}

相關推薦

NGINX配置以及優化

1. Apache伺服器和nginx的優缺點: 我們之前大量使用Apache來作為HTTPServer。 Apache具有很優秀的效能,而且通過模組可以提供各種豐富的功能。 1)首先Apache對客戶端的響應是支援併發的 ,執行httpd這個daemon程序之後,它會同時產生多個孩子程序/執行緒,每個孩子程

nginx配置優化詳解

nginx優化(1)nginx運行工作進程個數,一般設置cpu的核心或者核心數x2如果不了解cpu的核數,可以top命令之後按1看出來,也可以查看/proc/cpuinfo文件 grep ^processor /proc/cpuinfo | wc -l [[email protected]/* *

Nginx配置優化(轉載)

cpu strong 資源 大並發 網站流量統計 調優 傳遞 超時時間 ipv (1)nginx運行工作進程個數,一般設置cpu的核心或者核心數x2 如果不了解cpu的核數,可以top命令之後按1看出來,也可以查看/proc/cpuinfo文件 grep ^processo

nginx 配置效能優化

nginx是一個高併發web伺服器,所以沒有很好的優化配置可能會產生效能瓶頸與安全問題。 1.隱藏nginx版本號,防止根據某個軟體版本漏洞來攻擊伺服器  在http模組中新增server_tokens off; 或者在nginx編譯安裝前改掉所有涉及版本號的檔案,具體有哪些檔案有版

tomcat自帶連線池dbcp配置以及優化說明

轉自:http://www.totcms.com/html/201602-29/20160229114145.htm 一個網站每天大概有20萬的訪問量,使用的tomcat自帶dbcp連線池,一般網站訪問很好,速度也很快,但是過一段時間後,總是報timeout waiting for idl

Nginx配置以及域名轉發

xlsx webp package csdn location hoc thml ffi ats 工程中的nginx配置 #user nobody; worker_processes 24; error_log /home/xxx/opt/nginx/lo

Nginx 配置優化詳解

(1)nginx執行工作程序個數,一般設定cpu的核心或者核心數x2 如果不瞭解cpu的核數,可以top命令之後按1看出來,也可以檢視/proc/cpuinfo檔案 grep ^processor /proc/cpuinfo | wc -l  [[email prot

nginx配置優化

    回憶了下以前nginx筆記,下面放上來一步步說,這裡主要為nginx伺服器軟體方面.     1.先上一些常用配置與說 # nginx程序數,建議按照cpu數目來指定,如,雙核四執行緒[邏輯4核],那麼設定數建議為4*2 = 8 --worke

Nginx配置效能優化

大多數的Nginx安裝指南告訴你如下基礎知識——通過apt-get安裝,修改這裡或那裡的幾行配置,好了,你已經有了一個Web伺服器了。而且,在大多數情況下,一個常規安裝的nginx對你的網站來說已經能很好地工作了。然而,如果你真的想擠壓出Nginx的效能,你必須更深入一些。

Nginx配置檔案優化詳解

Nginx配置檔案優化詳解 對nginx進行優化是重點也是難點,這裡給出一些常用的優化措施,以及相關引數的所代表的意思。

Nginx常用功能配置優化

nginx web服務器 優化----------------------------------------------------------------------------------------規範優化Nginx配置文件:--------------------------------------

nginx虛擬域名的配置以及測試驗證

control dir 技術分享 include 機器 dex con host class 1.保證該機器上安裝了nginx 未安裝請看:centos/linux下的安裝Nginx 2.使用root用戶編輯配置文件 vim /usr/local/nginx/conf/n

Nginx配置參數優化註解

nginx### For more information on configuration, see: ### * Official English Documentation: ### auther:luo.m ##nginx運行用戶 user nginx; ##pid路徑 pid /run/ngi

Nginx配置優化參考

val time 反向代理服務器 ngx php sof wid io性能 web服務 Nginx配置優化參考

Nginx配置優化及深入講解,大家可以聽一下

inactive 建立連接 epo 快速 一個 sync 檢測 wait 新建 隨著訪問量的不斷增加,需要對Nginx和內核做相應的優化來滿足高並發用戶的訪問,那下面在單臺Nginx服務器來優化相關參數。 1) Nginx.conf配置優化: worker_pr

Nginx配置優化解讀

head 本地 oct 監聽 efault local nofile 避免 mime 全局配置 Nginx的配置文件是nginx的安裝目錄的conf/nginx .conf,nginx.conf配置文件中,幾個全局高級配置在模塊部分之上。 user www www; wo

[Nginx] – 配置優化NGINX.CONF [三]

nginx配置文件 nginx優化 逗哥自動化 nginx 本文主要針對nginx.conf配置文件,下面就把相關配置文件放到下面進行逐一的解釋 1、user 語法: user user[group]; 標簽: main 定義user和工作group 進程使用的憑證。如果group省略,use

Nginx配置:防盜鏈、訪問控制、解析PHP以及代理

防盜鏈 訪問控制 Nginx代理 一、Nginx防盜鏈 防盜鏈是指一個網站的資源(圖片或附件)未經允許在其它網站提供瀏覽和下載,尤其熱門資源的盜鏈,對網站帶寬的消耗非常大,設置防盜鏈以節省資源。 1、修改虛擬主機配置文件 [root@zlinux vhost]# vim linuxtest.c

Web項目之Nginx配置文件優化

Nginx配置文體結構 優化目標: ----->>隱藏版本<<------------------------------ ----->>更改Nginx默認默認用戶<<---------- ----->>工作進程優化<<-------

Nginx在windows上安裝 及 Nginx配置優化

打開 兩種方法 agen OS 關閉 檢查 14. win 快速 1.下載nginxhttp://nginx.org/en/download.html 下載穩定版本,以nginx/Windows-1.12.2為例,直接下載 nginx-1.12.2.zip下