nginx初級安裝配置


實驗環境:系統 CENTOS5.5,用戶 root
目錄以yum默認安裝為參考

一、安裝
1、安裝epel源(安裝時注意版本選擇,此處為5.X 32位版)
rpm -ivh http://mirrors.ustc.edu.cn/fedora/epel//5/i386/epel-release-5-4.noarch.rpm
安裝nginx以及php模塊
yum install nginx php-fpm php-cgi

2、如果以前用的是apache,記得要停掉
/etc/init.d/httpd stop
chkconfig httpd --level 2345 off

3、啟動nginx
chkconfig httpd --level 2345 on
/etc/init.d/nginx start

二、常用操作
1、啟動
/usr/sbin/nginx -c /etc/nginx/nginx.conf
不使用-c指定配置文件的話,默認加載安裝目錄下conf/nginx.conf

2、停止
平衡停止
kill -QUIT <nginx pid>

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

3、重啟
/usr/sbin/nginx -s reload

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

4、配置文件檢查
/usr/sbin/nginx -t -c /etc/nginx/nginx.conf

5、查看版本
簡單顯示版本號
/usr/sbin/nginx -v

詳細顯示版本及config相關信息
/usr/sbin/nginx -V

三、基本配置
1、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
  {
    #詳見 站點配置
  }
}

2、去除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;

3、防止被綁定域名
server {
listen 80 default;
rewrite ^.* http://www.test.com permanent;    #此處域名指向自己主站,以引導網友訪問正確網站。
}

4、禁止某目錄下的某類文件訪問
location ~* ^/(<目錄名可以是正則>)/.*\.(<文件擴展名可以是正則>)$
{
deny all;
}
例如:
location ~* ^/(images|files)/.*\.(php|php3|php4|php5|cgi)$
{
deny all;
}

5、防止php_info BUG
編輯/usr/local/nginx/conf/fastcgi_params,首行添加如下內容
if ($request_filename ~* (.*)\.php)
{
  set $php_url $1;
}
if (!-e $php_url.php)
{
  return 403;
}

6、防旁注
各個虛擬主機目錄設為不易猜測的名字。
在php.ini中修改open_basedir值,設置為上傳文件的臨時目錄和各虛擬主機存放目錄(以冒號分隔)。
chmod 755 -R <虛擬主機目錄>
chmod 711 <虛擬主機目錄>

7、防盜鏈
以防圖片盜鏈為例,只要請求來源非www.test.com則一概返回403錯誤.
location ~* .(gif|jpg|png)$ {
valid_referers none blocked www.test.com;
if ($invalid_referer) {
return 403;
}
}

四、站點配置
  每組server{}是一個虛擬主機。
1、基於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;
  }
}

2、基於域名的虛擬主機
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;
  }
}

五、日志處理
1、log_format
基本格式:log_format <日志格式名> <格式定義串>
示例:log_format gzip '$remote_addr - $remote_user [$time_local] '
                '"$request" $status $bytes_sent '
                '"$http_referer" "$http_user_agent" "$gzip_ratio"';

2、access_log
基本格式: access_log <日志路徑> [日志格式名(通過log_format定義)] [buffer=SIZE];
示例:access_log /var/log/web/test.log gzip buffer=32k;

3、日志文件切割
·創建腳本,輸入以下內容,保存到恰當的位置,例如/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

六、rewrite處理
1、 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匹配的是(.*)。

2、return
基本格式:return <狀態碼>
返回狀態碼,包括204、400、402~406、408、410、411、413、416和500~504。

3、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),默認情況參數會自動附到替換串上,如果不需要附帶參數,則在替換串末尾加上“?”。

4、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后。


免責聲明!

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



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