【前言】:
编写此技术指南在于推广普及NGINX在国内的使用,更方便的帮助大家了解和掌握NGINX的一些使用技巧。本指南很多技巧来自于网络在此对网络上愿意分享的朋友们表示感谢和致意!欢迎大家和我一起丰富本技术指南并提出更好的建议!
Nginx专为性能优化而开发,性能是其最重要的考量, 实现上非常注重效率 。它支持内核Poll模型,能经受高负载的考验, 有报告表明能支持高达
50,000 个并发连接数。
Nginx具有很高的稳定性。其它HTTP服务器,当遇到访问的峰值,或者有人恶意发起慢速连接时,也很可能会导致服务器物理内存耗尽频繁交换,失去响
应,只能重启服务器。例如当前apache一旦上到200个以上进程,web响应速度就明显非常缓慢了。而Nginx采取了分阶段资源分配技术,使得它的
CPU与内存占用率非常低。nginx官方表示保持10,000个没有活动的连接,它只占2.5M内存,所以类似DOS这样的攻击对nginx来说基本上
是毫无用处的。就稳定性而言, nginx比lighthttpd更胜一筹。 Nginx支持热部署。它的启动特别容易,
并且几乎可以做到7*24不间断运行,即使运行数个月也不需要重新启动。你还能够 在不间断服务的情况下,对软件版本进行进行升级。
Nginx采用master-slave模型,
能够充分利用SMP的优势,且能够减少工作进程在磁盘I/O的阻塞延迟。当采用select()/poll()调用时,还可以限制每个进程的连接数。
Nginx代码质量非常高,代码很规范, 手法成熟, 模块扩展也很容易。特别值得一提的是强大的Upstream与Filter链。
Upstream为诸如reverse
proxy,与其他服务器通信模块的编写奠定了很好的基础。而Filter链最酷的部分就是各个filter不必等待前一个filter执行完毕。它可以
把前一个filter的输出做为当前filter的输入,这有点像Unix的管线。这意味着,一个模块可以开始压缩从后端服务器发送过来的请求,且可以在
模块接收完后端服务器的整个请求之前把压缩流转向客户端。 Nginx采用了一些os提供的最新特性如对sendfile (Linux
2.2+),accept-filter (FreeBSD 4.1+),TCP_DEFER_ACCEPT (Linux 2.4+)
的支持,从而大大提高了性能。
1、安装pcre代码: CODE:
./configure
make && make install
cd ../
2、 nginx 编译安装代码: CODE:
./configure -user=www -group=www -prefix=/usr/local/nginx/ -with-http_stub_status_module -with-openssl=/usr/local/openssl
make && make install
更详细的模块定制与安装请参照官方wiki.
* ~ 为区分大小写匹配
* ~* 为不区分大小写匹配
* !~和!~*分别为区分大小写不匹配及不区分大小写不匹配
* -f和!-f用来判断是否存在文件
* -d和!-d用来判断是否存在目录
* -e和!-e用来判断是否存在文件或目录
* -x和!-x用来判断文件是否可执行
$args
$content_length
$content_type
$document_root
$document_uri
$host
$http_user_agent
$http_cookie
$limit_rate
$request_body_file
$request_method
$remote_addr
$remote_port
$remote_user
$request_filename
$request_uri
$query_string
$scheme
$server_protocol
$server_addr
$server_name
$server_port
$uri
将所有linuxtone.org与abc.linuxtone.org域名全部自跳转到http://www.linuxtone.org代码: CODE:
server
{
listen 80;
server_name linuxtone.org abc.linuxtone.org;
index index.html index.php;
root /data/www/wwwroot;
if ($http_host !~ “^www\.linxtone\.org$”) {
rewrite ^(.*) [url]http://www.linuxtone.org[/url]$1 redirect;
}
……………………
}
代码: CODE:
if (-d $request_filename){
rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
}
CODE: Preventing hot linking of images and other file types
location ~* ^.+\.(gif|jpg|png|swf|flv|rar|zip)$ {
valid_referers none blocked server_names *.linuxtone.org http://localhost baidu.com;
if ($invalid_referer) {
rewrite ^/ [img]http://www.linuxtone.org/images/default/logo.gif[/img];
# return 403;
}
}
location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {
if (-f $request_filename) {
root /data/www/wwwroot/bbs;
expires 1d;
break;
}
}
location ~ ^/(images|javascript|js|css|flash|media|static)/ {
root /data/www/wwwroot/down;
expires 30d;
}
cd /usr/local/nginx/conf
mkdir htpasswd
/usr/local/apache2/bin/htpasswd -c /usr/local/nginx/conf/htpasswd/tongji linuxtone #添加用户名为linuxtone
New password: (此处输入你的密码)
Re-type new password: (再次输入你的密码)
Adding password for user
[url]http://count.linuxtone.org/tongji/data/index.html[/url](目录存在/data/www/wwwroot/tongji/data/目录下)
将下段配置放到虚拟主机目录,当访问[url]http://count.linuxtone/tongji/[/url]即提示要密验证:
location ~ ^/(tongji)/ {
root /data/www/wwwroot/count;
auth_basic ”LT-COUNT-TongJi”;
auth_basic_user_file /usr/local/nginx/conf/htpasswd/tongji;
}
location ~* \.(txt|doc)$ {
if (-f $request_filename) {
root /data/www/wwwroot/linuxtone/test;
break;
}
}
方法2:代码: CODE:
location ~* \.(txt|doc)${
root /data/www/wwwroot/linuxtone/test;
deny all;
}
禁止访问某个目录代码: CODE:
location ~ ^/(WEB-INF)/ {
deny all;
}
location / {
deny 192.168.1.1;
allow 192.168.1.0/24;
allow 10.1.1.0/16;
deny all;
}
详细参见wiki: http://wiki.codemongers.com/NginxHttpAccessModule#allow
limit_zone one $binary_remote_addr 10m;
server
{
listen 80;
server_name down.linuxotne.org;
index index.html index.htm index.php;
root /data/www/wwwroot/down;
#Zone limit
location / {
limit_conn one 1;
limit_rate 20k;
}
……….
}
location / {
autoindex on;
}
CODE:
location [=|~|~*|^~] /uri/ { … }
* ~ 为区分大小写匹配
* ~* 为不区分大小写匹配
* !~和!~*分别为区分大小写不匹配及不区分大小写不匹配
示例1:代码: CODE:
location = / {
# matches the query / only.
# 只匹配 / 查询。
}
匹配任何查询,因为所有请求都已 / 开头。但是正则表达式规则和长的块规则将被优先和查询匹配 示例2:代码: CODE:
location ^~ /images/ {
# matches any query beginning with /images/ and halts searching,
# so regular expressions will not be checked.# 匹配任何已 /images/ 开头的任何查询并且停止搜索。任何正则表达式将不会被测试。
}
示例3:代码: CODE:
location ~* \.(gif|jpg|jpeg)$ {
# matches any request ending in gif, jpg, or jpeg. However, all
# requests to the /images/ directory will be handled by
} 匹配任何已 gif、jpg 或 jpeg 结尾的请求。
#contab -e
59 23 * * * /usr/local/sbin/logcron.sh /dev/null 2>&1
[root@count ~]# cat /usr/local/sbin/logcron.sh代码:
CODE:
#!/bin/bash
log_dir=”/data/logs”
time=`date +%Y%m%d`
/bin/mv ${log_dir}/access_linuxtone.org.log ${log_dir}/access_count.linuxtone.org.$time.log
kill -USR1 `cat /var/run/nginx.pid`
更多的日志分析与处理就关注(同时欢迎你参加讨论):http://bbs.linuxtone.org/forum-8-1.html
location ~ .*\.(js|jpg|JPG|jpeg|JPEG|css|bmp|gif|GIF)$
{
access_log off;
}
如果需要将文件缓存到本地,则需要增加如下几个子参数: CODE:
proxy_store on;
proxy_store_access user:rw group:rw all:rw;
proxy_temp_path 缓存目录;其中,
proxy_store on用来启用缓存到本地的功能,
proxy_temp_path用来指定缓存在哪个目录下,如:proxy_temp_path html;
在经过上一步配置之后,虽然文件被缓存到了本地磁盘上,但每次请求仍会向远端拉取文件,为了避免去远端拉取文件,必须修改proxy_pass:
CODE:
if ( !-e $request_filename) {
proxy_pass http://mysvr;
}
即改成有条件地去执行proxy_pass,这个条件就是当请求的文件在本地的proxy_temp_path指定的目录下不存在时,再向后端拉取。
upstream bbs.linuxtone.org {#定义负载均衡设备的Ip及设备状态
server 127.0.0.1:9090 down;
server 127.0.0.1:8080 weight=2;
server 127.0.0.1:6060;
server 127.0.0.1:7070 backup;
}
在需要使用负载均衡的server中增加代码: CODE:
proxy_pass [url]http://bbs.linuxtone.org/[/url];
每个设备的状态设置为:代码: CODE:
1.down 表示单前的server暂时不参与负载
2.weight 默认为1.weight越大,负载的权重就越大。
3.max_fails :允许请求失败的次数默认为1.当超过最大次数时,返回proxy_next_upstream 模块定义的错误
4.fail_timeout:max_fails次失败后,暂停的时间。
5.backup: 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。nginx支持同时设置多组的负载均衡,用来给不用的server来使用。
client_body_in_file_only 设置为On 可以讲client post过来的数据记录到文件中用来做debug
client_body_temp_path 设置记录文件的目录 可以设置最多3层目录
location 对URL进行匹配.可以进行重定向或者进行新的代理 负载均衡
按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,后端服务器为缓存时比较有效,也可以用作提高Squid缓存命中率.
简单的负载均等实例: vi nginx.conf //nginx主配置文件核心配置代码: CODE:
……….
#loadblance my.linuxtone.org
upstream my.linuxtone.org {
ip_hash;
server 127.0.0.1:8080;
server 192.168.169.136:8080;
server 219.101.75.138:8080;
server 192.168.169.117;
server 192.168.169.118;
server 192.168.169.119;
}
…………..
include vhosts/linuxtone_lb.conf;
………
#vi proxy.conf
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
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 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;
proxy_max_temp_file_size 128m;
proxy_store on;
proxy_store_access user:rw group:rw all:r;
#nginx cache
client_body_temp_path /data/nginx_cache/client_body 1 2;
proxy_temp_path /data/nginx_cache/proxy_temp 1 2;#vi linuxtone_lb.conf
代码:
CODE:
server
{
listen 80;
server_name my.linuxtone.org;
index index.php;
root /data/www/wwwroot/mylinuxtone;
if (-f $request_filename) {
break;
}
if (-f $request_filename/index.php) {
rewrite (.*) $1/index.php break;
}
error_page 403 [url]http://my.linuxtone.org/member.php?m=user&a=login[/url];
location / {
if ( !-e $request_filename) {
proxy_pass [url]http://my.linuxtone.org[/url];
break;
}
include /usr/local/nginx/conf/proxy.conf;
}
}
# debug
CFLAGS=”$CFLAGS -g”
注释掉或删掉这几行,重新编译即可。
# cd nginx-0.6.31
# vi src/core/nginx.h
#ifndef _NGINX_H_INCLUDED_
#define _NGINX_H_INCLUDED_
#define NGINX_VERSION ”1.3″
#define NGINX_VER “LTWS/” NGINX_VERSION
#define NGINX_VAR “NGINX”
#define NGX_OLDPID_EXT “.oldbin”
#endif /* _NGINX_H_INCLUDED_ */
# curl -I my.linuxtone.org
HTTP/1.1 200 OK
Server: LTWS/1.3
Date: Mon, 24 Nov 2008 02:42:51 GMT
Content-Type: text/html; charset=gbk
Transfer-Encoding: chunked
Connection: keep-alive