Nginx日誌切割
如果任由訪問日誌寫下去,日誌文件會變得越來越大,甚至是寫滿磁盤。
所以,我們需要想辦法把日誌做切割,比如每天生成一個新的日誌,舊的日誌按規定時間刪除即可。
實現日誌切割可以通過寫shell腳本或者系統的日誌切割機制實現。
shell腳本切割Nginx日誌
切割腳本內容:
#!/bin/bash
logdir=/var/log/nginx //定義日誌路徑
prefix=`date -d "-1 day" +%y%m%d` //定義切割後的日誌前綴
cd $logdir
for f in `ls *.log`
do
mv $f $f-$prefix //把日誌改名
done
/bin/kill -USR1 $(cat /usr/local/nginx/logs/nginx.pid 2>/dev/null) 2>/dev/null //生成新的日誌
bzip2 *$prefix //壓縮日誌
find . -type f -mtime +180 |xargs /bin/rm -f //刪除超過180天的老日誌
系統日誌切割機制
在/etc/logrotate.d/下創建nginx文件,內容爲:
/data/logs/*log {
daily
rotate 30
missingok
notifempty
compress
sharedscripts
postrotate
/bin/kill -USR1 $(cat /usr/local/nginx/logs/nginx.pid 2>/dev/null) 2>/dev/null || :
endscript
}
說明:
- nginx日誌在/data/logs/目錄下面,日誌名字以log結尾
- daily表示每天切割
- rotate 30表示日誌保留30天
- missingok表示忽略錯誤
- notifempty表示如果日誌爲空,不切割
- compress表示壓縮
- sharedscripts和endscript中間可以引用系統的命令
- postrotate表示當切割之後要執行的命令
nginx監控
配置Nginx狀態
Nginx有內置一個狀態頁,需要在編譯的時候指定參數–with-http_stub_status_module參數方可打開。
也就是說,該功能是由http_stub_status_module模塊提供,默認沒有加載。
Nginx配置文件示例
server{
listen 80;
server_name www.aminglinux.com;
location /status/ {
stub_status on;
access_log off;
allow 127.0.0.1;
allow 192.168.10.0/24;
deny all;
}
}
配置說明
location /status/這樣當訪問/status/時即可訪問到狀態頁內容。
stub_status on即打開了狀態頁。
access_log off不記錄日誌
allow和deny只允許指定IP和IP段訪問,因爲這個頁面需要保護起來,並不公開,當然也可以做用戶認證。
測試和結果說明
測試命令:curl -x127.0.0.1:80 www.aminglinux.com/status/
結果如下:
Active connections: 1
server accepts handled requests
11 11 11
Reading: 0 Writing: 1 Waiting: 0
說明:
active connections – 活躍的連接數量
server accepts handled requests — 總共處理的連接數、成功創建的握手次數、總共處理的請求次數
需要注意,一個連接可以有多次請求。
reading — 讀取客戶端的連接數.
writing — 響應數據到客戶端的數量
waiting — 開啓 keep-alive 的情況下,這個值等於 active – (reading+writing), 意思就是 Nginx 已經處理完正在等候下一次請求指令的駐留連接.
配置Nginx和php
配置如下(在server部分添加):
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/tmp/php-fcgi.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
配置說明:
- fastcgi_params文件在/usr/local/nginx/conf/下面,其內容爲fastcgi相關的變量
- fastcgi_pass後面跟的是php-fpm服務監聽地址,可以是IP:PORT,也可以是unix socket地址,也支持upstream的地址
- fastcgi_index定義索引頁,如果在server內其他部分有定義index參數,該配置可以忽略
- fastcgi_param這行其實可以在fastcgi_params文件裏面定義SCRIPT_FILENAME變量,這個變量如果不定義,php的請求是沒辦法訪問的。
Nginx+Tomcat架構
配置文件示例
server
{
listen 80;
server_name www.aminglinux.com;
location ~* "\.(jpg|png|jepg|js|css|xml|bmp|swf|gif|html)$"
{
root /data/wwwroot/aminglinux/;
access_log off;
expire 7d;
}
location /
{
proxy_pass http://127.0.0.1:8080/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
說明:
- 首先,把各種靜態文件的請求分離出來,單獨由nginx處理。
- 其他請求直接代理8080端口,即tomcat服務。