nginx初級安裝配置

實驗環境:系統 CENTOS5.5,用戶 root
javascript

目錄以yum默認安裝爲參考php


1、安裝css

一、安裝epel源(安裝時注意版本選擇,此處爲5.X 32位版)html

rpm -ivh http://mirrors.ustc.edu.cn/fedora/epel//5/i386/epel-release-5-4.noarch.rpmjava

安裝nginx以及php模塊node

yum install nginx php-fpm php-cgilinux


二、若是之前用的是apache,記得要停掉nginx

/etc/init.d/httpd stopweb

chkconfig httpd --level 2345 offapache


三、啓動nginx

chkconfig httpd --level 2345 on

/etc/init.d/nginx start


2、經常使用操做

一、啓動

/usr/sbin/nginx -c /etc/nginx/nginx.conf

不使用-c指定配置文件的話,默認加載安裝目錄下conf/nginx.conf


二、中止

平衡中止

kill -QUIT <nginx pid>

kill -QUIT `cat /var/run/nginx.pid`


三、重啓

/usr/sbin/nginx -s reload

kill -HUP `cat /var/run/nginx.pid`


四、配置文件檢查

/usr/sbin/nginx -t -c /etc/nginx/nginx.conf


五、查看版本

簡單顯示版本號

/usr/sbin/nginx -v


詳細顯示版本及config相關信息

/usr/sbin/nginx -V


3、基本配置

一、nginx.conf基礎配置

#工做用戶及用戶組(根據機器環境修改配置)
user nginx nginx;
#工做進程數(通常設爲CPU總核數或其兩倍)
worker_processes 8;
#錯誤日誌路徑及記錄級別(debug,info,notice,warn,error,crit)
error_log /var/log/nginx/error.log warn;
#pid保存路徑
pid /var/run/nginx.pid;
#文件描述符數
worker_rlimit_nofile 51200;
events
{
 #使用的網絡I/O模型,linux推薦epoll模型,freebsd推薦kqueue模型
 use epoll;
 #容許的鏈接數,能夠的話儘可能設大一些
 worker_connections 51200;
}
http
{
 include /etc/niginx/mime.types;
 defaut_type application/octet-stream;
 #默認字符集,如不肯定網站字符集,則不要設置,經過html的meta標籤指定。
 charset utf-8;
 #禁止錯誤頁面裏顯示nginx的版本號
 server_tokens off;
 server_names_hash_bucket_size 128;
 client_header_buffer_size 32k;
 large_client_header_buffers 4 32k;
 #客戶端上傳文件大小限制
 client_max_body_size 8m;
 sendfile on;
 tcp_nopush on;
 #客戶端鏈接超時,服務器將關閉鏈接。
 keepalive_timeout 60;
 tcp_nodelay on;
 #開啓gzip壓縮
 gzip on;
 #小於設置大小的文件不壓縮
 gzip_min_length 1k;
 gzip_buffers 4 16k;
 gzip_http_version 1.1;
 #壓縮等級
 gzip_comp_level 2;
 #壓縮文件的類型
 gzip_types text/plain application/x-javascript text/css application/xml;
 gzip_vary on;
 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;
 #指定是否傳遞錯誤信息到客戶端,或者容許nginx使用error_page處理錯誤信息。
 fastcgi_intercept_errors off;
 server
 {
  #詳見 站點配置
 }
}

二、去除fastcgi中nginx版本號相關設置

編輯/usr/local/nginx/conf/fastcgi.conf和/usr/local/nginx/conf/fastcgi_params

將fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;改爲fastcgi_param SERVER_SOFTWARE nginx;


三、防止被綁定域名

server {

listen 80 default;

rewrite ^.* http://www.test.com permanent; #此處域名指向本身主站,以引導網友訪問正確網站。

}


四、禁止某目錄下的某類文件訪問

location ~* ^/(<目錄名能夠是正則>)/.*\.(<文件擴展名能夠是正則>)$

{

deny all;

}

例如:

location ~* ^/(p_w_picpaths|files)/.*\.(php|php3|php4|php5|cgi)$

{

deny all;

}


五、防止php_info BUG

編輯/usr/local/nginx/conf/fastcgi_params,首行添加以下內容

if ($request_filename ~* (.*)\.php)

{

  set $php_url $1;

}

if (!-e $php_url.php)

{

  return 403;

}


六、防旁註

各個虛擬主機目錄設爲不易猜想的名字。

在php.ini中修改open_basedir值,設置爲上傳文件的臨時目錄和各虛擬主機存放目錄(以冒號分隔)。

chmod 755 -R <虛擬主機目錄>

chmod 711 <虛擬主機目錄>


七、防盜鏈

以防圖片盜鏈爲例,只要請求來源非www.test.com則一律返回403錯誤.

location ~* .(gif|jpg|png)$ {

valid_referers none blocked www.test.com;

if ($invalid_referer) {

return 403;

}

}


4、站點配置

每組server{}是一個虛擬主機。

一、基於IP的虛擬主機

server
{
 #監聽IP及端口
 listen 192.168.1.2:80;
 #主機名
 server_name 192.168.1.2;
 #日誌文件存放路徑
 access_log logs/host.access.log main;
 location /
 {
   #默認首頁文件,從左至右匹配
   index index.html index.htm;
   #網站目錄
   root /opt/web/server1;
 }
}

二、基於域名的虛擬主機

server
{
 #監聽端口
 listen 80;
 #主機名,表示處理全部test1.test.com、test2.test.com以及*.test.cn域名的訪問。
 server_name test1.test.com test2.test.com *.test.cn;
 #日誌文件存放路徑
 access_log logs/host.access.log main;
 location /
 {
   index index.html index.htm;
   root /opt/web/server1;
 }
}

5、日誌處理

一、log_format

基本格式:log_format <日誌格式名> <格式定義串>

示例:log_format gzip '$remote_addr - $remote_user [$time_local] '

'"$request" $status $bytes_sent '

'"$http_referer" "$http_user_agent" "$gzip_ratio"';


二、access_log

基本格式: access_log <日誌路徑> [日誌格式名(經過log_format定義)] [buffer=SIZE];

示例:access_log /var/log/web/test.log gzip buffer=32k;


三、日誌文件切割

·建立腳本,輸入如下內容,保存到恰當的位置,例如/opt/cut_log.sh

#! /bin/bash

#功能說明:自動分割壓縮日誌文件,保存最近15天日誌

EXPIRES_DAY=15

BAK_NAME=$(date -d "yesterday" +"%Y%m%d")

LOG_PARENT_PATH="/var/log/nginx/"

LOG_PATH="access/"

mkdir -p ${LOG_PARENT_PATH}${LOG_PATH}

mv ${LOG_PARENT_PATH}access.log ${LOG_PARENT_PATH}${LOG_PATH}${BAK_NAME}.log

kill -USR1 `cat /var/run/nginx.pid`

cd ${LOG_PARENT_PATH}${LOG_PATH} && tar -czf ${BAK_NAME}.tgz ${BAK_NAME}.log

rm -f ${LOG_PARENT_PATH}${LOG_PATH}${BAK_NAME}.log

find ${LOG_PARENT_PATH}${LOG_PATH} -name '*.tgz' -ctime ${EXPIRES_DAY} -exec rm {} \;


·添加到計劃任務,天天0時0分自動執行

crontab -u root -e

0 0 * * * /opt/cut_log.sh


6、rewrite處理

一、 if

基本格式:if (<判斷條件>){...}

不能嵌套,不能多條件判斷

支持的判斷條件:

~ 區分大小寫

~* 不區分大小寫

-f 判斷文件是否存在

-d 判斷目錄是否存在

-e 判斷文件或目錄是否存在

-x 判斷文件是否可執行

判斷符前加!表示不匹配,如!-f 表示匹配文件不存在

和括號中正則匹配的內容,以後能夠用變量$1至$9調用,好比:

if ($request_uri ~* "/test/(\d+)\.html")

{

set $numb $1;

rewrite ^(.*)$ /msie/$1/$numb.html break;

}

注:上例中有兩個匹配項,set $numb $1;中的$1匹配的是"/test/(\d+)\.html"中的(\d+)。

rewrite ^(.*)$ /msie/$1/$numb.html break;中的$1匹配的是(.*)。


二、return

基本格式:return <狀態碼>

返回狀態碼,包括20四、400、402~40六、40八、4十、4十一、41三、416和500~504。


三、rewrite

基本格式:rewrite <正則式> <修改後的連接> <標誌>

重定向符合標準的連接至修改後的連接。

重寫表達式只對相對路徑有效。例如:

#訪問URL: http://www.test.com/main/index.htm

if ($host ~* www\.(.*))

{

set $host_without_www $1;

rewrite ^(.*)$ http://$host_without_www$1 permanent; #此處$1的內容爲"/main/index.htm"

}


標誌定義:

last:完成rewrite,使用alias指令時必須用此標記。

break:此規則匹配完成後,終止匹配。使用proxy_pass指令時使用此標記。

redirect:302重定向。

permanent:301重定向。

last在本條rewrite規則執行完後,會對所在的server{}從新發請求,而break則在匹配完後終止匹配。

所以,通常在location /{}或直接在server{}中的rewrite規則裏使用last,在非根location中使用break。

如URI中有參數(例:http://www.test.com/index.htm?id=10),默認狀況參數會自動附到替換串上,若是不須要附帶參數,


則在替換串末尾加上「?」。


四、set

基本格式:set <變量名> <值>

用於定義變量或變量賦值。例如:

set $name 'lykyl';


附: nginx支持的信號

TERM INT 快速關閉

QUIT 從容關閉

HUP 平滑重啓

USR1 從新打開或創建日誌文件

USR2 平滑升級可執行程序

WINCH 從容關閉工做進程


附:nginx日誌變量

$body_bytes_sent the number of bytes sent to a client not counting the response header; this variable is


compatible with the 「%B」 parameter of the mod_log_config Apache module

$bytes_sent the number of bytes sent to a client

$connection connection serial number

$connection_requests the current number of requests made through a connection

$msec time in seconds with a milliseconds resolution at the time of log write

$pipe 「p」 if request was pipelined, 「.」 otherwise

$request_length request length (including request line, header, and request body)

$request_time request processing time in seconds with a milliseconds resolution; time elapsed between the


first bytes were read from the client and the log write after the last bytes were sent to the client

$status response status

$time_iso8601 local time in the ISO 8601 standard format

$time_local local time in the Common Log Format


附:nginx rewrite全局變量

$arg_PARAMETER 包含GET請求中,若是有變量PARAMETER時的值。

$args 請求行中(GET請求)的參數。

$binary_remote_addr #二進制的客戶地址。

$body_bytes_sent #響應時送出的body字節數數量。即便鏈接中斷,這個數據也是精確的。

$content_length #請求頭中的Content-length字段。

$content_type #請求頭中的Content-Type字段。

$cookie_COOKIE #cookie COOKIE變量的值

$document_root #當前請求在root指令中指定的值。

$document_uri #與$uri相同。

$host #請求主機頭字段,不然爲服務器名稱。

$hostname #Set to the machine’s hostname as returned by gethostname

$http_HEADER

$is_args #若是有$args參數,這個變量等於」?」,不然等於」",空值。

$http_user_agent #客戶端agent信息

$http_cookie #客戶端cookie信息

$limit_rate #這個變量能夠限制鏈接速率。

$query_string #與$args相同。

$request_body_file #客戶端請求主體信息的臨時文件名。

$request_method #客戶端請求的動做,一般爲GET或POST。

$remote_addr #客戶端的IP地址。

$remote_port #客戶端的端口。

$remote_user #已經通過Auth Basic Module驗證的用戶名。

$request_completion #若是請求結束,設置爲OK. 當請求未結束或若是該請求不是請求鏈串的最後一個時,爲空(Empty)。

$request_method #GET或POST

$request_filename #當前請求的文件路徑,由root或alias指令與URI請求生成。

$request_uri #包含請求參數的原始URI,不包含主機名,如:」/foo/bar.php?arg=baz」。不能修改。

$scheme #HTTP方法(如http,https)。

$server_protocol #請求使用的協議,一般是HTTP/1.0或HTTP/1.1。

$server_addr #服務器地址,在完成一次系統調用後能夠肯定這個值。

$server_name #服務器名稱。

$server_port #請求到達服務器的端口號。

$uri #不帶請求參數的當前URI,$uri不包含主機名,如」/foo/bar.html」。該值有可能和$request_uri 不一致。


$request_uri是瀏覽器發過來的值。該值是rewrite後的值。例如作了internal redirects後。


(lykyl原創,轉載請註明出處)

相關文章
相關標籤/搜索