Nginx 配置实例
作为一个轻量级的HTTP服务器,Nginx与Apache相比有以下优势:在性能上,它占用很少的系统资源,能支持更多的并发连接,达到更高的访问效率;在功能上,Nginx是的代理服务器和负载均衡服务器;在安装配置上,Nginx安装简单、配置灵活。下面以实例介绍Nginx 配置。
Nginx 配置虚拟主机
下面在Nginx中创建3个虚拟主机,需要说明的是,这里仅仅列出了虚拟主机的Nginx 配置。
http{
server{
listen 80;
server_name www.zzidc.com
access_log logs/zzidc.access.log main;
location / {
index index.html;
root /web/www/zzidc.com/htdocs;
}
}
server{
listen 80;
server_name www.zzidc1.com
access_log logs/zzidc1.access.log main;
location / {
index index.html;
root /web/www/zzidc1.com/htdocs;
}
}
include /opt/nginx/conf/vhosts/www.zzidc1.com.conf;
}
这里用到了include指令,其中/opt/nginx/conf/vhosts/www.zzidc1.com.conf的内容如下:
server{
listen 80;
server_name www.zzidc2.com
access_log logs/zzidc2.access.log main;
location / {
index index.html;
root /web/www/zzidc2.com/htdocs;
}
}
Nginx 配置负载均衡
下面通过Nginx的反向代理功能配置一个Nginx负载均衡服务器。后端3个服务节点,用于提供web服务,通过Nginx的调度实现3个节点负载均衡。
http
{
upstream myserver{
server 192.168.12.181:80 weight=3 max_fails=3 fail_timeout=20s;
server 192.168.12.181:80 weight=1 max_fails=3 fail_timeout=20s;
server 192.168.12.181:80 weight=4 max_fails=3 fail_timeout=20s;
}
server
{
listen 80;
server_name www.zzidc.com 192.168.12.189;
index index.htm index.html;
root /indba/web/wwwroot;
location / {
proxy_pass http://myserver
proxy_next_upstream http_500 http_502 http_503 error timeout invalid_header;
include /opt/nginx/conf/proxy.conf;
}
}
Nginx 配置防盗链
Nginx的防盗链功能也非常强大。在默认情况下,只需要进行简单的配置,即可实现防盗链处理。请看下面的Nginx 配置防盗链实例:
location -* .(jgp|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
valid_referers none blocked *.ixdba1.net ixdba1.net;
if($invalid_referer) {
rewrite / http://www.zzidc.com/img/error.gif
#return 403
}
}
location /images {
root /opt/nginx/html:
valid_referers none blocked * .zzidc1.com zzidc1.com
if($invalid_referer){
return 403;
}
}
Nginx 配置日志分割
Nginx没有类似Apache的cronolog日志分割处理的功能,但是,可以通过Nginx的信号控制功能的脚本来实现日志的自动切割。请看Nginx 配置日志分割实例。
Nginx对日志进行处理的脚本
#/bin/bash
savepath_log=‘/home/nginx/logs’
nglogs = '/opt/nginx/logs'
mkdir -p $savepath_log/$(date +%¥)/$(date +%m)
mv $nglogs/access.log $savepath_log/$(data +%¥)/$(date +%m)/access.$(date +%¥%m%d).log
mv $nglogs/error.log $savepath_log/$(data +%¥)/$(date +%m)/access.$(date +%¥%m%d).log
kill -USPI 'cat /opt/nginx/logs/nginx.pid'
将这段脚本保存后加入到Lin的crontab守护进程,让此脚本在每天凌晨0点执行,可以实现日志的每天分割功能了。