【前言】:编写此技术指南在于推广普及NGINX在国内的使用,更方便的帮助大家了解和掌握NGINX的一些使用技巧。本指南很多技巧来自于网络和工作中或网络上朋友们问我的问题.在此对网络上愿意分享的朋友们表示感谢和致意!欢迎大家和我一起丰富本技术指南提
【前言】:
编写此技术指南在于推广普及NGINX在国内的使用,更方便的帮助大家了解和掌握NGINX的一些使用技巧。
本指南很多技巧来自于网络和工作中或网络上朋友们问我的问题.在此对网络上愿意分享的朋友们表示感
谢和致意!欢迎大家和我一起丰富本技术指南提出更好的建议!
一、 Nginx 基础知识
1、简介
Nginx (“engine x”) 是一个高性能的 HTTP 和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服
务器。 Nginx 是由 Igor Sysoev 为俄罗斯访问量第二的 Rambler.ru 站点开发的,它已经在该站点运行
超过两年半了。Igor 将源代码以类BSD许可证的形式发布。尽管还是测试版,但是,Nginx 已经因为它的
稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名了。
更多的请见官方wiki: http://wiki.codemongers.com/
2、 Nginx的优点
nginx做为HTTP服务器,有以下几项基本特性:
1) 处理静态文件,索引文件以及自动索引;打开文件描述符缓冲.
2) 无缓存的反向代理加速,简单的负载均衡和容错.
3) FastCGI,简单的负载均衡和容错.
4) 模块化的结构。包括gzipping, byte ranges, chunked responses, 以及 SSI-filter等filter。如果
由FastCGI或其它代理服务器处理单页中存在的多个SSI,则这项处理可以并行运行,而不需要相互等待。
5) 支持SSL 和 TLS SNI.
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+) 的支持,从而大大提高了性能
二、 Nginx 安装及调试
1、Pcre 安装
./configure
make && make install
cd ../
2、nginx 编译安装
./configure –user=www –group=www –prefix=/usr/local/nginx/ –with-http_stub_status_module
–with-openssl=/usr/local/openssl
make && make install
更详细的模块定制与安装请参照官方wiki.
3、Nginx 配置文件测试:
# /usr/local/nginx/sbin/nginx -t //Debug 配置文件的关键命令需要重点撑握.
2008/12/16 09:08:35 [info] 28412#0: the configuration file /usr/local/nginx/conf/nginx.conf
syntax is ok
2008/12/16 09:08:35 [info] 28412#0: the configuration file /usr/local/nginx/conf/nginx.conf
was tested successfully
4、Nginx 启动:
# /usr/local/nginx/sbin/nginx
5、Nginx 配置文件修改重新加载:
# kill -HUP `cat /usr/local/nginx/logs/nginx.pid
`
三、Nginx Rewrite
1. Nginx Rewrite 基本标记(flags)
last – 基本上都用这个Flag。
※相当于Apache里的[L]标记,表示完成rewrite,不再匹配后面的规则
break – 中止Rewirte,不再继续匹配
redirect – 返回临时重定向的HTTP状态302
permanent – 返回永久重定向的HTTP状态301
※原有的url支持正则 重写的url不支持正则
2. 正则表达式匹配,其中:
* ~ 为区分大小写匹配
* ~* 为不区分大小写匹配
* !~和!~* 分别为区分大小写不匹配及不区分大小写不匹配
3. 文件及目录匹配,其中:
* -f和!-f用来判断是否存在文件
* -d和!-d用来判断是否存在目录
* -e和!-e用来判断是否存在文件或目录
* -x和!-x用来判断文件是否可执行
3. Nginx 的一些可用的全局变量,可用做条件判断:
$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
四、 Nginx Redirect
将所有linuxso.com与netseek.linuxso.com域名全部自跳转到http://www.linuxso.com
server
{
listen 80;
server_name linuxso.com netseek.linuxso.com;
index index.html index.php;
root /data/www/wwwroot;
if ($host !~ “^www.linxtone.org$”) {
rewrite ^(.*) http://www.linuxso.com$1 redirect;
}
……………………
}
五、 Nginx 目录自动加斜线:
if (-d $request_filename){
rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
}
或者
server_name_in_redirect off;
六 Nginx Location
1.基本语法:[和上面rewrite正则匹配语法基本一致]
location [=|~|~*|^~] /uri/ { … }
* ~ 为区分大小写匹配
* ~* 为不区分大小写匹配
* !~和!~*分别为区分大小写不匹配及不区分大小写不匹配
示例1:
location = / {
# matches the query / only.
# 只匹配 / 查询。
}
匹配任何查询,因为所有请求都已 / 开头。但是正则表达式规则和长的块规则将被优先和查询匹配
示例2:
location ^~ /images/ {
# matches any query beginning with /images/ and halts searching,
# so regular expressions will not be checked.
# 匹配任何已 /images/ 开头的任何查询并且停止搜索。任何正则表达式将不会被测试。
示例3:
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 结尾的请求。
补充:
?明1:location = /uri/ {…}
?ふ抑环??uri/的??t,如果找到後即停止搜?ぁ?/p>
?明2:location ~ /uri/ {…}
?ふ?^分大小??的正?表示式。
?明3:location ~* /uri/ {…}
?ふ也?^分大小??的正?表示式。
?明4:location ^~ /uri/ {…}
用於 常?字符,符合常?字符後不再使用正常表示式。
七、 Nginx expires
1.根据文件类型expires
# Add expires header for static content
location ~* .(js|css|jpg|jpeg|gif|png|swf)$ {
if (-f $request_filename) {
root /data/www/wwwroot/bbs;
expires 1d;
break;
}
}
2、根据判断某个目录
# serve static files
location ~ ^/(images|Javascript|js|css|flash|media|static)/ {
root /data/www/wwwroot/down;
expires 30d;
}
八、 Nginx 防盗链
1. 针对不同的文件类型
#Preventing hot linking of images and other file types
location ~* ^.+.(gif|jpg|png|swf|flv|rar|zip)$ {
valid_referers none blocked server_names *.linuxso.com linuxso.com http://localhost
baidu.com;
if ($invalid_referer) {
rewrite ^/ ;
# return 403;
}
}
2. 针对不同的目录
location /img/ {
root /data/www/wwwroot/bbs/img/;
valid_referers none blocked server_names *.linuxso.com http://localhost baidu.com;
if ($invalid_referer) {
rewrite ^/ ;
#return 403;
}
}
3. 同实现防盗链和expires的方法
#Preventing hot linking of images and other file types
location ~* ^.+.(gif|jpg|png|swf|flv|rar|zip)$ {
valid_referers none blocked server_names *.linuxso.com linuxso.com http://localhost ;
if ($invalid_referer) {
rewrite ^/ ;
}
access_log off;
root /data/www/wwwroot/bbs;
expires 1d;
break;
}
九、 Nginx 访问控制
1. Nginx 身份证验证
首先在nginx.conf加入
location ~ ^/script/ {
auth_basic “welcome to key0.cn”;
auth_basic_user_file /var/www/test/script/.htpasswd;
}
# mkdir /var/www/test/script
# perl -e ‘print(crypt(key0,cn).”n”);’cnx9InAYT9uuM
# echo ‘kindle:cnx9InAYT9uuM’ > /var/www/test/script/.htpasswd
# /usr/local/nginx/sbin/nginx -s reload
2. Nginx 禁止访问某类型的文件.
如,Nginx下禁止访问*.txt文件,配置方法如下.
location ~* .(txt|doc)$ {
if (-f $request_filename) {
root /data/www/wwwroot/linuxtone/test;
#rewrite …..可以重定向到某个URL
break;
}
}
方法2:
location ~* .(txt|doc)${
root /data/www/wwwroot/linuxtone/test;
deny all;
}
实例:
禁止访问某个目录
location ~ ^/(WEB-INF)/ {
deny all;
}
3. 使用ngx_http_access_module限制ip访问
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
4. Nginx 下载限制并发和速率
limit_zone linuxtone $binary_remote_addr 10m;
server
{
listen 80;
server_name down.linuxotne.org;
index index.html index.htm index.php;