发布于 2016-06-27 00:45:24 | 258 次阅读 | 评论: 0 | 来源: 网友投递
Nginx WEB服务器
Nginx 是一个高性能的 HTTP 和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服务器。 Nginx 是由 Igor Sysoev 为俄罗斯访问量第二的 Rambler.ru 站点开发的,第一个公开版本0.1.0发布于2004年10月4日。其将源代码以类BSD许可证的形式发布,因它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名。
原本准备换Linux服务器,所以数据迁移暂时需要使用静态页面临时代替一下,之前的article.asp?id=xxx都要重定向到静态文件 article/xxx.htm,nginx的rewrite比apache的强大很多,还可以用if语句,很容易理解,下面看看Nginx是如何进行Rewrite的!
提示:以下rewrite指令写在 nginx.conf 配置的 server { … } 中
最常见的: 静态地址重定向到带参数的动态地址
rewrite "^(.*)/service/(.*)/.html$" $1/service.php?sid=$2 permanent;
反过来: 带参数的动态地址重定向到静态地址
if ($query_string ~* id=(.*)) {
set $id $1;
rewrite "^(.*)/article.asp$" $1/article/$id.htm last;
}
泛域名
假设这里网站的目录结构为
html
├── bbs
└── www
html为nginx的安装目录下默认的存放源代码的路径。
bbs为论坛程序源代码路径
www为主页程序源代码路径
把相应程序放入上面的路径通过
http://www.youdomain.com 访问的就是主页
http://bbs.yourdomain.com 访问的就是论坛
其它二级域名类推。
server_name www.w3cgroup.com *.w3cgroup.com;
server_name_in_redirect off;
#设置默认root
set $rootdir /usr/local/nginx/html/w3cgroup/;
#匹配三级域名
if ($host ~* ^([^/.]+)/.([^/.]+)/.([^/.]+)/.([^/.]+)$) {
set $rootdir /usr/local/nginx/html/w3cgroup/$2/$1;
#三级域名中有访问指定的目录则重定向到相应的二级域名下
rewrite "^.+upload/?(.*)$" http://upload.w3cgroup.com/$1 permanent;
rewrite "^.+ijc/?(.*)$" http://ijc.w3cgroup.com/$1 permanent;
break;
}
#匹配二级域名
if ($host ~* ^([^/.]+)/.([^/.]+)/.([^/.]+)$) {
set $rs1 $1;
}
#设置www时root
if ($rs1 ~* ^www$) {
set $rootdir /usr/local/nginx/html/platform_ig/;
#二级域名中有访问指定的目录则重定向到相应的二级域名下,注意,这里要使用last
rewrite "^.+upload/?(.*)$" upload/$1 last;
rewrite "^.+ijc/?(.*)$" ijc/$1 last;
break;
}
#设置非www二级域名时root
if ($rs1 !~* ^www$) {
set $rootdir /usr/local/nginx/html/w3cgroup/$rs1;
#二级域名中有访问指定的目录则重定向到相应的二级域名下
rewrite "^.+upload/?(.*)$" http://upload.w3cgroup.com/$1 permanent;
rewrite "^.+ijc/?(.*)$" http://ijc.w3cgroup.com/$1 permanent;
break;
}
#应用root
root $rootdir;
index index.php index.html;
error_page 404 http://$host/;
注意:if () {} 之间需要空格,否则Nginx.conf会报unknow directive 错误!
参考:
Nginx Rewrite Flags
Nginx正则表达式匹配
Nginx文件及目录匹配
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