nginx 实现反向代理
nginx 较常用的功能
VMWare Workstation 里面装的Centos6.5,Nginx1.8.1(安装见上一篇:Nginx的安装)
示例一:基于IP的虚拟主机
增加一个网卡地址(原机器是192.168.56.129)
ifconfig eth0:0 192.168.56.130
建立两个测试网站
mkdir /website1 #站点目录
mkdir /website2
mkdir /website1/log #日志存放目录
mkdir /website2/log
echo "this is website1" >/website1/index.html #建立静态测试index页面
echo "this is website2" >/website2/index.html
修改Nginx 配置文件,两个server节点,分别配置 location 和log,server节点配置如下:
# ----server1 ----
server {
listen 192.168.56.129:80;
server_name localhost;
#charset koi8-r;
access_log /website1/log/access.log;
error_log /website1/log/error.log;
location / {
root /website1;
index index.html index.htm;
}
}
# ----server2 ----
server {
listen 192.168.56.130:80;
server_name localhost;
#charset koi8-r;
access_log /website2/log/access.log;
error_log /website2/log/error.log;
location / {
root /website2;
index index.html index.htm;
}
}
重启nginx
/usr/local/nginx1.8.1/sbin/nginx -s stop
/usr/local/nginx1.8.1/sbin/nginx &
在浏览器里面输入192.168.56.129 和192.168.56.130,分别看到如下页面
示例2:基于主机头(域名)的配置
修改nginx.conf的server1节点
# ----server1 ----
server {
listen 192.168.56.129:80;
server_name www.website1.com;
#charset koi8-r;
access_log /website1/log/access.log;
error_log /website1/log/error.log;
location / {
root /website1;
index index.html index.htm;
}
}
重启nginx
/usr/local/nginx1.8.1/sbin/nginx -s stop
/usr/local/nginx1.8.1/sbin/nginx &
然后修改客户端host文件(c:/windows/system32/drivers/etc),hosts文件末尾增加
192.168.56.129 www.website1.com
然后在浏览器里输入www.website1.com,效果如下图:
无法访问的,可以重启DNS Client 服务试试
配置远程服务
可以随便用其他线上服务,本示例用以前的一个tomcat服务,如下
修改nginx.conf的server2节点
server {
listen 80;
server_name www.website2.com;
location / {
proxy_pass http://88.88.88.88:8088;
proxy_redirect default;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
重启nginx
/usr/local/nginx1.8.1/sbin/nginx -s stop
/usr/local/nginx1.8.1/sbin/nginx &
然后修改客户端host文件(c:/windows/system32/drivers/etc),hosts文件末尾增加
192.168.56.130 www.website2.com
浏览器端输入www.website2.com 或者192.168.56.130 ,效果如下(对照上图):