您的位置:首页 > 运维架构 > Nginx

nginx配置详解

2014-03-16 22:26 741 查看
Nginx(发音同 engine x)是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like 协议下发行。由俄罗斯的程序设计师Igor Sysoev所开发,最初供俄国大型的入口网站及搜寻引擎Rambler使用。其特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页伺服器中表现较好。一、安装nginx1. 添加nginx用户
[root@web ~]# groupadd -r nginx
[root@web ~]# useradd -r -M -s /sbin/nologin -g nginx nginx
2. 安装nginx
[root@web ~]# tar xf nginx-1.4.6.tar.gz
[root@web ~]# cd nginx-1.4.6
[root@web nginx-1.4.6]# ./configure   --prefix=/usr/local/ \
--sbin-path=/usr/sbin/nginx \
--conf-path=/etc/nginx/nginx.conf \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--pid-path=/var/run/nginx/nginx.pid \
--lock-path=/var/lock/nginx.lock \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_flv_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--http-client-body-temp-path=/var/tmp/nginx/client/ \
--http-proxy-temp-path=/var/tmp/nginx/proxy/ \
--http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \
--with-pcre=/root/pcre-8.32
[root@web nginx-1.4.6]# make && make install
3. 为nginx添加启动脚本
#!/bin/sh
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig:   - 85 15
# description:  Nginx is an HTTP(S) server, HTTP(S) reverse \
#               proxy and IMAP/POP3 proxy server
# processname: nginx
# config:      /etc/nginx/nginx.conf
# config:      /etc/sysconfig/nginx
# pidfile:     /var/run/nginx.pid
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0
nginx="/usr/sbin/nginx"
prog=$(basename $nginx)
NGINX_CONF_FILE="/etc/nginx/nginx.conf"
[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx
lockfile=/var/lock/subsys/nginx
make_dirs() {
# make required directories
user=`nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
options=`$nginx -V 2>&1 | grep 'configure arguments:'`
for opt in $options; do
if [ `echo $opt | grep '.*-temp-path'` ]; then
value=`echo $opt | cut -d "=" -f 2`
if [ ! -d "$value" ]; then
# echo "creating" $value
mkdir -p $value && chown -R $user $value
fi
fi
done
}
start() {
[ -x $nginx ] || exit 5
[ -f $NGINX_CONF_FILE ] || exit 6
make_dirs
echo -n $"Starting $prog: "
daemon $nginx -c $NGINX_CONF_FILE
retval=$?
echo
[ $retval -eq 0 ] && touch $lockfile
return $retval
}
stop() {
echo -n $"Stopping $prog: "
killproc $prog -QUIT
retval=$?
echo
[ $retval -eq 0 ] && rm -f $lockfile
return $retval
}
restart() {
configtest || return $?
stop
sleep 1
start
}
reload() {
configtest || return $?
echo -n $"Reloading $prog: "
killproc $nginx -HUP
RETVAL=$?
echo
}
force_reload() {
restart
}
configtest() {
$nginx -t -c $NGINX_CONF_FILE
}
rh_status() {
status $prog
}
rh_status_q() {
rh_status >/dev/null 2>&1
}
case "$1" in
start)
rh_status_q && exit 0
$1
;;
stop)
rh_status_q || exit 0
$1
;;
restart|configtest)
$1
;;
reload)
rh_status_q || exit 7
$1
;;
force-reload)
force_reload
;;
status)
rh_status
;;
condrestart|try-restart)
rh_status_q || exit 0
;;
*)
echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
exit 2
esac
4. 简单配置和启动
[root@web ~]# vim /etc/nginx/nginx.conf
user nginx;
pid         /var/run/nginx.pid;
[root@web ~]# service nginx restart
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Stopping nginx:                                            [  OK  ]
Starting nginx:                                            [  OK  ]
二. 配置nginx1) location语法规则: location [=|~|~*|^~] /uri/ { … }
=表示精确匹配,不会去匹配子目录下的文件
~表示区分大小写的正则匹配
~*表示不区分大小写的正则匹配
^~表示不做正则表达式匹配
/表示通用匹配,任何请求都会匹配到
2) root语法规则:root PATH (可以用在http、server、location中)root用来指定网站的根目录3)alias语法规则:alias file-path|directory-pathalias的普通用法:location /alias/test.html {alias /web/alias/test.html;}使用正则表达式的alias:location ~ ^/test/(.*)$ {alias /var/nginx/test/$1;}如果root在/var/www/html下,而访问http://domain/alias/test.html这个目录时,就会访问web下alias/test.htmlroot和alias的区别:root指定的目录就是location后面的“/”,而alias指定的目录需要包括location后面的路径,如上面的例子。4) index语法规则:index index.html index.htm; #指定主页文件autoindex on; #索引功能打开,当没有找到定义的主页文件时,就会把网站跟目录下的文件都列出来5) 基于主机的访问控制allow [ address | CIDR | all ]deny [ address | CIDR | all ]例子:location / {root /var/www/html;index index.html index.htm;allow 192.168.2.0/24;deny all;}6) 定义虚拟主机
server {
listen      80 default;
server_name    _;
location / {
root        /var/nginx/test;
index      index.html;
}
}
server {
listen       80;
server_name  www.aa.com;
location / {
root   /var/www/html;
index  index.html index.htm;
}
}
#定义了2个虚拟主机,上面一个是默认虚拟主机
7) 基于用户认证的nginx监控
[root@web ~]# htpasswd -m -c /etc/nginx/.htpasswd maria
[root@web ~]# vim /etc/nginx/nginx.conf
location /nginx_status {
stub_status on;             #打开监控功能
access_log off;             #关闭日志
auth_basic "who are you?";  #认证时的提示信息
auth_basic_user_file /etc/nginx/.htpasswd;  #认证的文件
}
#在编译时需添加--with-http_stub_status_module这个模块,才可以开启监控
8)URL重写语法规则: rewrite regex replacement flagflag的种类:
last把当前的重写指令执行结束,并且重新启动匹配进程,一般都是用last
break中止Rewirte,不在继续匹配
redirect返回临时重定向的HTTP状态302
permanent返回永久重定向的HTTP状态301
统一资源定位符(URL)和统一资源标识符(URI):www.aa.com/nginx/a.html,对于这个地址,可以理解为这个地址就是一个URL,/nignx/a.html就是URI。就相当于一个绝对路径,一个相对路径。例子: http://www.aa.com/maria.php?id=123 #用户请求的地址 http://www.aa.com/123/maria #重写后的地址rewrite ^/(maria)\.php\?id=(.*)$ /$2/$1 last; #书写方法,前面匹配的就是URI9)if语句语法规则: if (condition) { ... }应用环境: server, locationcongdition:1、变量名; false values are: empty string ("", or any string starting with "0";)2、对于变量进行的比较表达式,可使用=或!=进行测试;3、正则表达式的模式匹配:~ 区分大小的模式匹配~* 不区分字母大小写的模式匹配!~ 和 !~* 分别对上面的两种测试取反4、测试文件是否存在-f或!-f5、测试目录是否存在-d或!-d6、测试目录、文件或链接文件的存在性-e或!-e7、检查一个文件的执行权限-x或!-x简单应用:
#实现域名跳转
server
{
listen 80;
server_name jump.aa.com;
index index.html index.php;
root /var/www/html;
rewrite ^/ http://www.aa.com/; }
#简单的防盗链配置:
location ~* \.(gif|jpg|png|swf|flv)$ {
valid_referers none blocked www.aa.com;
if ($invalid_referer) {
rewrite ^/ http://www.aa.com/403.html; # return 404
}
}
10) 日志管理语法规则: log_format name formatⅠ、设定错误日志格式及级别:
http {
log_format my_log_fm '$http_x_forwarded_for - $remote_user [$time_local]'
'"$request" $status $body_bytes_sent'
'"$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log my_log_fm;
error_log /var/log/nginx/error.log warn;
}
$http_x_forwarded_for
和$remote_user用于记录客户端网关的IP地址和用户$time_local用于记录访问时间和时区$request用于记录请求的URL和http协议$status用于记录请求的状态,例如请求成功时状态码为200$body_bytes_sent用于记录发送给客户端文件主体的内容大小$http_referer用户记录请求是从哪个页面连接访问过来的$http_user_agent用户记录客户端浏览器的相关信息Ⅱ、记录类似apache格式的日志:
log_format main '$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/access.log main;
Ⅲ、启用日志缓存:open_log_file_cache max=100 inactive=30s min_uses=2 valid=1m;
max最多在缓存中最大文件描述符的数量
inactive在固定时间内没有被访问过的文件描述符,就从缓存中移除
min_uses在inactive的时间内,被访问的最少次数,满足这个次数才放到缓存中
vaild检查缓存中的日志在磁盘上是否还存在,m表示分钟
off关闭日志缓存功能
Ⅳ、日志切割nginx的日志文件没有rotate功能。如果你不处理,日志文件将变得越来越大,可以用脚本+crontab来进行日志切割。
[root@web ~]# vim log_switch.sh
#!/bin/bash
#
logs_path="/var/log/nginx/"
#当前日志的存放目录
mkdir -p ${logs_path}$(date -d"yesterday" +"%Y")/$(date -d"yesterday" +"%m")
#在上面的目录下,给日志创建以时间命名的目录
mv ${logs_path}aa.access.log ${logs_path}$(date -d"yesterday" +"%Y")/$(date -d"yesterday" +"%m")/$(date -d"yest
erday" +"%Y%m%d").log
#移动日志到日期命名的目录中
service nginx reload
[root@web ~]# crontab -e
00 00 * * * /root/log_switch.sh
11. 设定限速
#为某个特定路径限速
server {
server_name www.aa.com;
location /downloads/ {
limit_rate 256k;
limit_rate_after 20m;
root /var/www/html;
}
..
}
#限制搜索引擎的速度
if ($http_user_agent ~ Google|Yahoo|MSN|baidu) {
limit_rate 128k;
}
limit_rate_after
20m表示下载的前20M不做限速[/code]
limit_rate限制速度为256K/s
12. 为反向代理启用缓存功能
http {proxy_cache_path  /data/nginx/cache  levels=1:2    keys_zone=STATIC:10minactive=24h  max_size=1g;server {location / {proxy_pass             http://192.168.2.87; proxy_set_header       Real-ip $remote_addr;proxy_cache            STATIC;proxy_cache_valid      200  1d;   #对响应码为200的文件,指定缓存失效的检查时间client_max_body_size 50m;client_body_buffer_size 256k;proxy_connect_timeout 30;proxy_send_timeout 30;proxy_read_timeout 60;proxy_buffer_size 256k;proxy_buffers 4 256k;proxy_busy_buffers_size 256k;proxy_temp_file_write_size 256k;proxy_cache_use_stale  error timeout invalid_header updatinghttp_500 http_502 http_503 http_504;}}}
levels 指定该缓存空间有两层hash目录,第一层目录为1个字母,第二层为2个字母keys_zone=STATIC:1m 参数用来为这个缓存区起名(proxy_cache 指令需要用到其后对应缓存区名称),:1m 指内存缓存空间大小为1MBinactive=24h指如果缓存数据在24小时(天:d、秒:s、分:m)内没有被访问,将自动被删除max_size=1g 指硬盘缓存大小为1g13. 负载均衡功能
  upstream backend {server www.aa.com weight=5 down [backup];server 127.0.0.1:8080     max_fails=3  fail_timeout=30s;server unix:/tmp/backend3;}
weight 设定权重,默认为1max_fails 在fail_timeout指令设定的时间内发往此server的不成功的请求次数,达到此数目后,此服务器将变为不可操作状态;默认值为1;设定为0值则禁用此功能;fail_timeout 默认为10秒;down 列表中有这个服务器,但是不启用它backup 当其他负载均衡的服务器都挂了,才会启用backup
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息