nginx的反向代理
作者:bin原理:
客户端请求外部服务器=>反向代理接受请求=>转发=>内部服务器=>得到结果=>返回给客户端
优点是,外部服务器会将返回结果缓存在本地,这样同样的请求,就不再请求内部服务器,这样就减轻了内部服务器的压力
1、多域名跳转
配合location的匹配,可以将url路由至指定域名或ip下,示例:
server www.ben.com
location / {
proxy_pass http://192.168.1.2/web #将www.ben.com指向http://192.168.1.2/web
}
location /admin {
proxy_pass http://192.168.1.3/admin #将www.ben.com/admin,指向http://192.168.1.2/admin
}
server www.benmobile.com
location / {
proxy_pass http://192.168.1.4/mobile #将www.benmobile.com 指向http://192.168.1.4/mobile
}
2、通过nginx重定向实现新旧域名过度
server
{
listen 80;
server_name dev.zengbingo.com;
rewrite ^/(.*)$ http://www.baidu.com/$1 permanent;
}
输入:https://dev.zengbingo.com/?name=zengbin
跳转:https://www.baidu.com/?name=zengbin
也可以通过nginx核心变量host去判断
server
{
listen 80;
server_name dev.zengbingo.com www.zsenbgin.com;
if ($host != 'www.zsenbgin.com') {
rewrite ^/(.*)$ http://www.baidu.com/$1 permanent;
}
}
这里值得注意的是permanent:永久重定向,direct:临时重定向;
3、alias在nginx下的应用
server
{
listen 80;
server_name dev.zengbingo.com;
location /ben{
alias /home/ben/$1;
}
}
请求url location后面部分会被追加到alias指定到目录后面
例如:http://dev.zengbingo.com/ben/package.xml
请求位置:/home/ben/package.xml