Nginx動(dòng)態(tài)化舉例分析

這篇文章主要講解了“Nginx動(dòng)態(tài)化舉例分析”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“Nginx動(dòng)態(tài)化舉例分析”吧!

目前創(chuàng)新互聯(lián)公司已為數(shù)千家的企業(yè)提供了網(wǎng)站建設(shè)、域名、網(wǎng)站空間成都網(wǎng)站托管、企業(yè)網(wǎng)站設(shè)計(jì)、江油網(wǎng)站維護(hù)等服務(wù),公司將堅(jiān)持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長(zhǎng),共同發(fā)展。

環(huán)境:

CentOS 6.4 ip:192.168.1.113 域名:www.sunsky.com(server和client都通過(guò)hosts文件解析) nginx-1.2.9 編譯安裝,路徑/usr/local/nginx,服務(wù)開(kāi)啟狀態(tài) 日志記錄格式為nginx默認(rèn)的,切勿更改,否則會(huì)造成awstats無(wú)法分析日志。 log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; awstats-7.2.tar.gz CPAN-2.00.tar.gz FCGI-0.74.tar.gz FCGI-ProcManager-0.24.tar.gz 必須有perl-devel,不然無(wú)法編譯FCGI。

一、日志自動(dòng)切割

對(duì)于nginx的日志切割,由于沒(méi)有像apache一樣去用cronolog工具,這里我們就寫(xiě)一個(gè)腳本,讓它可以在每天00:01自動(dòng)執(zhí)行,切割昨天的日志(交由awstats分析),壓縮前天的日志(壓縮日志可減小存儲(chǔ)空間,為防止awstats沒(méi)有分析完就被壓縮,所以只壓縮前天的日志)。

vim /server/scripts/cut_nginx_log.sh

輸入以下內(nèi)容:

#!/bin/sh yesterday=`date -d "yesterday" +"%Y%m%d"` before_yesterday=`date -d "-2 day" +"%Y%m%d"` Nginx_Dir="/usr/local/nginx" Nginx_logs="/app/logs" Log_Name="www_access" cd /tmp [ -d $Nginx_Logs ] && cd $Nginx_logs || exit 1 [ -f $Log_Name.log ] && /bin/mv $Log_Name.log ${Log_Name}_${yesterday}.log || exit 1 if [ $? -eq 0 -a -f $Nginx_Dir/logs/nginx.pid ] then kill -USR1 `cat $Nginx_Dir/logs/nginx.pid` fi [ -f  ${Log_Name}_${before_yesterday}.log ] && /usr/bin/gzip ${Log_Name}_${before_yesterday}.log|| exit 1

執(zhí)行crontab -e將該腳本加入定時(shí)任務(wù)中

1 0 * * * /bin/sh /server/scripts/cut_nginx_log.sh >/dev/null 2>&1

這樣每天凌晨00:01就能自動(dòng)實(shí)現(xiàn)日志的切割,壓縮等功能了。

因?yàn)楸敬螌?shí)驗(yàn)下的nginx此時(shí)已經(jīng)有日志了,另外為了后文awstats能對(duì)切割過(guò)的日志進(jìn)行分析,所以這里我們要運(yùn)行一下此腳本,來(lái)將現(xiàn)有日志進(jìn)行切割生成昨天的日志方便后文操作。

/bin/sh /server/scripts/cut_nginx_log.sh >/dev/null 2>&1

二、配置FCGI

1、安裝CPAN

wget http://search.cpan.org/CPAN/authors/id/A/AN/ANDK/CPAN-2.00.tar.gz tar zxf CPAN-2.00.tar.gz cd CPAN-2.00 perl Makefile.PL make && make install

2、安裝FCGI和FCGI::ProcManager

wget http://search.cpan.org/CPAN/authors/id/F/FL/FLORA/FCGI-0.74.tar.gz tar zxf FCGI-0.74.tar.gz cd FCGI-0.74 第一種安裝方法:perl -MCPAN -e 'install FCGI' 第二種安裝方法:perl Makefile.PL               make&&make install wget http://search.cpan.org/CPAN/authors/id/B/BO/BOBTFISH/FCGI-ProcManager-0.24.tar.gz tar zxf FCGI-ProcManager-0.24.tar.gz cd FCGI-ProcManager-0.24 第一種安裝方法:perl -MCPAN -e 'install FCGI::ProcManager' 第二種安裝方法:perl Makefile.PL               make&&make install

在執(zhí)行第一種安裝方法的時(shí)候,一定是全程自動(dòng)滾動(dòng)下來(lái)提示OK的。如果出現(xiàn)提示你輸入yes之類的,你需要按提示操作完之后,再運(yùn)行第二次直到全程自動(dòng)滾動(dòng)下來(lái)提示OK才為完成安裝?;蛘吣憔陀玫诙N方法來(lái)執(zhí)行安裝。

3、創(chuàng)建FCGI啟動(dòng)文件

vi /usr/local/nginx/sbin/fcgi       #此處按個(gè)人習(xí)慣命名 #!/usr/bin/perl use FCGI; #perl -MCPAN -e 'install FCGI' use Socket; use POSIX qw(setsid); #use Fcntl; require 'syscall.ph'; &daemonize; #this keeps the program alive or something after exec'ing perl scripts END() { } BEGIN() { } *CORE::GLOBAL::exit = sub { die "fakeexit\nrc=".shift()."\n"; }; eval q{exit}; if ($@) {         exit unless $@ =~ /^fakeexit/; }; &main; sub daemonize() {     chdir '/'                 or die "Can't chdir to /: $!";     defined(my $pid = fork)   or die "Can't fork: $!";     exit if $pid;     setsid                    or die "Can't start a new session: $!";     umask 0; } sub main { #$socket = FCGI::OpenSocket( "127.0.0.1:8999", 10 ); $socket = FCGI::OpenSocket( "/usr/local/nginx/fastcgi_temp/perl_cgi-dispatch.sock", 10 ); #use UNIX sockets - user running this script must have w access to the 'nginx' folder!! $request = FCGI::Request( \*STDIN, \*STDOUT, \*STDERR, \%req_params, $socket ); if ($request) { request_loop()}; FCGI::CloseSocket( $socket ); } sub request_loop { while( $request->Accept() >= 0 ) {                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #processing any STDIN input from WebServer (for CGI-POST actions) $stdin_passthrough =''; $req_len = 0 + $req_params{'CONTENT_LENGTH'}; if (($req_params{'REQUEST_METHOD'} eq 'POST') && ($req_len != 0) ){ my $bytes_read = 0; while ($bytes_read < $req_len) { my $data = ''; my $bytes = read(STDIN, $data, ($req_len - $bytes_read)); last if ($bytes == 0 || !defined($bytes)); $stdin_passthrough .= $data; $bytes_read += $bytes;  } } #running the cgi app if ( (-x $req_params{SCRIPT_FILENAME}) && #can I execute this? (-s $req_params{SCRIPT_FILENAME}) && #Is this file empty? (-r $req_params{SCRIPT_FILENAME})     #can I read this file? ){ pipe(CHILD_RD, PARENT_WR); my $pid = open(KID_TO_READ, "-|"); unless(defined($pid)) { print("Content-type: text/plain\r\n\r\n"); print "Error: CGI app returned no output - Executing $req_params {SCRIPT_FILENAME} failed !\n"; next; } if ($pid > 0) { close(CHILD_RD); print PARENT_WR $stdin_passthrough; close(PARENT_WR); while(my $s = <KID_TO_READ>) { print $s; } close KID_TO_READ; waitpid($pid, 0); } else { foreach $key ( keys %req_params){ $ENV{$key} = $req_params{$key}; } # cd to the script's local directory if ($req_params{SCRIPT_FILENAME} =~ /^(.*)\/[^\/]+$/) { chdir $1; } close(PARENT_WR); close(STDIN); #fcntl(CHILD_RD, F_DUPFD, 0); syscall(&SYS_dup2, fileno(CHILD_RD), 0); #open(STDIN, "<&CHILD_RD"); exec($req_params{SCRIPT_FILENAME}); die("exec failed");           }        } else { print("Content-type: text/plain\r\n\r\n"); print "Error: No such CGI app - $req_params{SCRIPT_FILENAME} may not exist or is not executable by this process.\n";        }    } }

創(chuàng)建完成后,需要賦予fcgi執(zhí)行權(quán)限:

chmod 755 /usr/local/nginx/sbin/fcgi

啟動(dòng)FPM(FastCGI 進(jìn)程管理器)

perl /usr/local/nginx/sbin/fcgi >/dev/null 2>$1

在這里,Nginx需要對(duì)fcgi生成的/usr/local/nginx/fastcgi_temp/perl_cgi-dispatch.sock有讀寫(xiě)權(quán)限,否則會(huì)報(bào)502錯(cuò)誤。

三、Awstats的安裝與配置

1、部署awstats

首先我們要下載awstats軟件包,并將其放在常規(guī)目錄(/usr/local)下:

wget http://awstats.sourceforge.net/files/awstats-7.2.tar.gz tar zxf awstats-7.2.tar.gz mv awstats-7.2 /usr/local/awstats

由于wget下載下來(lái)的包中權(quán)限是非root的,所以這里要修改權(quán)限,否則稍后*.pl將無(wú)法運(yùn)行:

chown -R root.root /usr/local/awstats chmod +x /usr/local/awstats/tools/*.pl chmod +x /usr/local/awstats/wwwroot/cgi-bin/*.pl

接下來(lái)我們要執(zhí)行awstats/tools下的awstats_configure.pl配置向?qū)В脕?lái)生成awstats的配置文件,awstats配置文件的命名規(guī)則是awstats.website.conf

cd /usr/local/awstats/tools/ ./awstats_configure.pl

此時(shí)會(huì)出現(xiàn)如下提示:

----- AWStats awstats_configure 1.0 (build 1.9) (c) Laurent Destailleur ----- This tool will help you to configure AWStats to analyze statistics for one web server. You can try to use it to let it do all that is possible in AWStats setup, however following the step by step manual setup documentation (docs/index.html) is often a better idea. Above all if: - You are not an administrator user, - You want to analyze downloaded log files without web server, - You want to analyze mail or ftp log files instead of web log files, - You need to analyze load balanced servers log files, - You want to 'understand' all possible ways to use AWStats... Read the AWStats documentation (docs/index.html). -----> Running OS detected: Linux, BSD or Unix -----> Check for web server install Enter full config file path of your Web server. Example: /etc/httpd/httpd.conf Example: /usr/local/apache2/conf/httpd.conf Example: c:\Program files\apache group\apache\conf\httpd.conf Config file path ('none' to skip web server setup): > none      #這里讓填寫(xiě)網(wǎng)頁(yè)服務(wù)器的配置文件路徑,因?yàn)槲覀冇玫牟皇莂pache,所以這里要填none Your web server config file(s) could not be found. You will need to setup your web server manually to declare AWStats script as a CGI, if you want to build reports dynamically. See AWStats setup documentation (file docs/index.html) -----> Update model config file '/usr/local/awstats/wwwroot/cgi-bin/awstats.model.conf'   File awstats.model.conf updated. -----> Need to create a new config file ? Do you want me to build a new AWStats config/profile file (required if first install) [y/N] ? y         #詢問(wèn)是否創(chuàng)建一個(gè)新的配置文件,這里填y -----> Define config file name to create What is the name of your web site or profile analysis ? Example: www.mysite.com Example: demo Your web site, virtual server or profile name: > www.sunsky.com      #這里讓填寫(xiě)你的網(wǎng)站域名,虛擬主機(jī)名或者隨便一個(gè)配置名 -----> Define config file path In which directory do you plan to store your config file(s) ? Default: /etc/awstats Directory path to store config file(s) (Enter for default): >              #這里要填寫(xiě)你配置文件存放路徑,我們使用它默認(rèn)的路徑/etc/awstats,所以直接回車(chē)即可 -----> Create config file '/etc/awstats/awstats.www.sunsky.com.conf'  Config file /etc/awstats/awstats.www.sunsky.com.conf created. -----> Add update process inside a scheduler Sorry, configure.pl does not support automatic add to cron yet. You can do it manually by adding the following command to your cron: /usr/local/awstats/wwwroot/cgi-bin/awstats.pl -update -config=www.sunsky.com Or if you have several config files and prefer having only one command: /usr/local/awstats/tools/awstats_updateall.pl now Press ENTER to continue...   #提示不能自動(dòng)加入crontab定時(shí)任務(wù),需要稍后自己添加,我們按回車(chē)?yán)^續(xù)即可 A SIMPLE config file has been created: /etc/awstats/awstats.www.sunsky.com.conf You should have a look inside to check and change manually main parameters. You can then manually update your statistics for 'www.sunsky.com' with command: > perl awstats.pl -update -config=www.sunsky.com You can also build static report pages for 'www.sunsky.com' with command: > perl awstats.pl -output=pagetype -config=www.sunsky.com Press ENTER to finish... #提示配置文件創(chuàng)建完成和如何更新配置及建立靜態(tài)報(bào)告頁(yè),這里我們回車(chē)即可結(jié)束這個(gè)配置向?qū)?/pre>

2、修改awstats配置文件

完成配置文件的創(chuàng)建之后,我們還需要對(duì)/etc/awstats/awstats.www.sunsky.com.conf里的一些參數(shù)進(jìn)行修改。

sed -i 's#LogFile="/var/log/httpd/mylog.log"#LogFile="/app/logs/www_access_%YYYY-24%MM-24%DD-24.log"#g' /etc/awstats/awstats.www.sunsky.com.conf

這里更改的目的是指定awstats需要分析的nginx的日志文件路徑。這里的路徑大家要按自己的日志路徑來(lái)填。

sed -i 's#DirData="/var/lib/awstats"#DirData="/usr/local/awstats/data"#g'/etc/awstats/awstats.www.sunsky.com.conf

這里更改的目的是指定awstats的數(shù)據(jù)庫(kù)配置文件(即awstats的數(shù)據(jù)庫(kù)(純文本))。

由于,此處沒(méi)有/usr/local/awstats/data目錄,所以我們要?jiǎng)?chuàng)建出來(lái):

mkdir /usr/local/awstats/data

以上的兩個(gè)替換操作進(jìn)行完之后一定要用命令查看替換是否成功,以便及早發(fā)現(xiàn)紕漏。

grep "LogFile=" /etc/awstats/awstats.www.sunsky.com.conf grep "DirData=" /etc/awstats/awstats.www.sunsky.com.conf

查詢替換結(jié)果正確之后,即可進(jìn)行下面的步驟。

3、生成awstats統(tǒng)計(jì)信息數(shù)據(jù)庫(kù)

現(xiàn)在我們需要用awstats來(lái)生成對(duì)日志的統(tǒng)計(jì)分析信息出來(lái)了。由于我們用的是支持perl的FCGI動(dòng)態(tài)化訪問(wèn)頁(yè)面,所以此處我們只需要直接更新數(shù)據(jù)庫(kù)即可。FCGI程序會(huì)自動(dòng)將數(shù)據(jù)庫(kù)以動(dòng)態(tài)頁(yè)面的形式展現(xiàn)出來(lái),無(wú)須再手動(dòng)生成靜態(tài)頁(yè)面了。本處我們用腳本來(lái)完成。

vim /server/scripts/awstats_up.sh #!/bin/sh /usr/local/awstats/wwwroot/cgi-bin/awstats.pl -update -config=www.sunsky.com >/dev/null 2>&1

該腳本里面用下面的命令也是可以的。

/usr/local/awstats/tools/awstats_updateall.pl now

運(yùn)行該腳本生成分析結(jié)果

/bin/sh /server/scripts/awstats_up.sh

四、配置日志分析頁(yè)面的來(lái)訪ip的地址位置顯示

這里我們用國(guó)內(nèi)最準(zhǔn)確的ip數(shù)據(jù)庫(kù)&mdash;&mdash;QQ純真庫(kù)我在博客附件里面放了這個(gè)工具,大家下載之后通過(guò)CRT用lrzsz工具傳上去,具體步驟這里不寫(xiě)了。

附件里面有三個(gè)文件qqhostinfo.pm,qqwry.pl和QQWry.Dat,我們將這三個(gè)文件統(tǒng)統(tǒng)都放到/usr/local/awstats/wwwroot/cgi-bin/plugins中。

接下來(lái),我們修改qqwry.pl文件,將./QQWry.Dat修改為${DIR}/plugins/QQWry

vim /usr/local/awstats/wwwroot/cgi-bin/plugins/qqwry.pl #my $ipfile="./QQWry.Dat";

修改為:

my $ipfile="${DIR}/plugins/QQWry.Dat ";

然后編輯awstats的配置文件/etc/awstats/awstats.www.sunsky.com.conf(根據(jù)你前面配置的站點(diǎn)信息生成的文件),將LoadPlugin="hostinfo"替換為L(zhǎng)oadPlugin="qqhostinfo"即可。

sed -i 's#\#LoadPlugin="hostinfo"#LoadPlugin="qqhostinfo"#g'/etc/awstats/awstats.www.sunsky.com.conf

切記,在這些替換完之后一定要查看替換是否成功,以便及早發(fā)生紕漏。

grep "LoadPlugin=\"qqhostinfo\"" /etc/awstats/awstats.www.sunsky.com.conf

如果檢查無(wú)誤,那么我們的ip地址位置顯示就配置好了,在后面的日志分析中,我們就可以清楚的看到來(lái)訪ip的地理位置信息了。

五、配置nginx

接下來(lái)我們要配置nginx使其能安全的訪問(wèn)到分析的數(shù)據(jù)

vim /usr/local/nginx/conf/nginx.conf

在server{}內(nèi)添加如下內(nèi)容:

server {            listen 80;            server_name www.sunsky.com;             location / {             root   /www/sunsky;             index  index.html index.htm;             access_log  /app/logs/www_access.log  main;     }             location ~* ^/cgi-bin/.*\.pl$ {             root /usr/local/awstats/wwwroot;                fastcgi_pass unix:/usr/local/nginx/fastcgi_temp/perl_cgi-dispatch.sock;                fastcgi_index index.pl;                include  fastcgi_params;                charset gb2312;                auth_basic "Restricted";       #有些網(wǎng)站不愿意公開(kāi)網(wǎng)站流量信息,所以加個(gè)認(rèn)證                auth_basic_user_file /usr/local/nginx/htpasswd.pass;  #該文件由apache的加密認(rèn)證工具h(yuǎn)tpasswd創(chuàng)建            }       location ~ ^/icon/ {          root   /usr/local/awstats/wwwroot/;          index index.html;          access_log off;          error_log off;          charset gb2312;       } }

為了保持nginx.conf主配置文件更加整潔干凈,所以我們將fastcgi_param的一系列參數(shù)添加到/usr/local/nginx/conf/fastcgi_params文件的最頂部,然后在nginx.conf里面調(diào)用這個(gè)文件即可。

vi /usr/local/nginx/conf/fastcgi_params 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 GATEWAY_INTERFACE CGI/1.1; fastcgi_param SERVER_SOFTWARE    nginx; 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 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; fastcgi_read_timeout 60;

針對(duì)上面的加密,由于nginx沒(méi)有好的加密認(rèn)證工具,需要借助apache的htpasswd來(lái)實(shí)現(xiàn)加密認(rèn)證功能:

htpasswd -c -m /usr/local/nginx/htpasswd.pass sunskyadmin      #用戶名為sunskyadmin

配置完畢之后,檢查nginx語(yǔ)法,然后優(yōu)雅重啟之后,用游覽器訪問(wèn)http://www.sunsky.com/cgi-bin/awstats.pl?config=www.sunsky.com,輸入賬號(hào)密碼之后即可查看統(tǒng)計(jì)信息了。

Nginx動(dòng)態(tài)化舉例分析

Nginx動(dòng)態(tài)化舉例分析

至此,awstats已經(jīng)可以實(shí)現(xiàn)對(duì)Nginx的日志統(tǒng)計(jì),動(dòng)態(tài)化安全訪問(wèn)及來(lái)訪ip的地址位置顯示等功能了。

五、配置awstats自動(dòng)運(yùn)行

為了讓整個(gè)日志的統(tǒng)計(jì)過(guò)程可以實(shí)現(xiàn)自動(dòng)化,將awstats.sh腳本加入crontab定時(shí)任務(wù)中去,此時(shí)結(jié)合上面的定時(shí)切割任務(wù),我們的crontab里面會(huì)有多出來(lái)兩條定時(shí)任務(wù)。

1 0 * * * /bin/sh /server/scripts/cut_nginx_log.sh >/dev/null 2>&1 0 1 * * * /bin/sh /server/scripts/awstats_up.sh >/dev/null 2>&1

感謝各位的閱讀,以上就是“Nginx動(dòng)態(tài)化舉例分析”的內(nèi)容了,經(jīng)過(guò)本文的學(xué)習(xí)后,相信大家對(duì)Nginx動(dòng)態(tài)化舉例分析這一問(wèn)題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

標(biāo)題名稱:Nginx動(dòng)態(tài)化舉例分析
URL網(wǎng)址:http://muchs.cn/article0/phodio.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計(jì)公司、網(wǎng)站導(dǎo)航、網(wǎng)站收錄、網(wǎng)站內(nèi)鏈網(wǎng)站建設(shè)定制開(kāi)發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

營(yíng)銷型網(wǎng)站建設(shè)