Nginx占用内存少,并且并发能力强,可以用于做反向代理和静态服务器。Nginx的主要用途有:
- 静态资源服务器
- 虚拟主机
- 反向代理服务器
- 负载均衡服务器
其中Nginx做静态资源服务器在上篇博客中已经介绍过了,这里主要介绍虚拟主机、反向代理和负载均衡的实现
Nginx实现虚拟主机
1.端口实现虚拟主机
虚拟主机其实就是在一台服务器上可以实现对外提供多种服务,如下图所示
物理主机只有一台,但是我们可以通过不同的端口号,域名等方式访问不同的服务资源,具体的配置如下
1.修改nginx.conf文件,我这边的改动如下
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index0.html index.htm;
}
}
server {
listen 81;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index1.html index.htm;
}
}
这里使用不同的端口号来划分虚拟主机,其中的root表示nginx目录下的html文件夹。我们可以新建index0.html和index1.html,然后重启nginx
cd ./sbin
./nginx -s reload
这样访问不同的端口就能访问到index0和index1了。
2.ip实现虚拟主机
配置文件如下
server {
listen 80;
server_name 192.168.80.40;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index0.html index.htm;
}
}
server {
listen 80;
server_name 192.168.80.50;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index1.html index.htm;
}
}
这里需要虚拟机绑定两个ip地址,如果访问的是192.168.80.40,则显示index0.html,如果访问的是192.168.80.50,则显示index1.html
3.使用域名实现虚拟主机
server {
listen 80;
server_name www.image.taozi.com;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index0.html index.htm;
}
}
server {
listen 80;
server_name www.music.taozi.com;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index1.html index.htm;
}
}
然后需要修改本机的/etc/host文件,做本机的ip地址映射,我的配置如下
192.168.181.148 www.image.taozi.com www.music.taozi.com
这样使用不同的域名访问的资源文件也不一样,这是最常用的方式
Nginx实现反向代理
反向代理(Reverse Proxy)实际运行方式是指以代理服务器来接受internet上的连接请求, 然后将请求转发给内部网络上的服务器,并将从服务器上得到的结果返回给 internet 上请求连接的客户端,此时代理服务器对外就表现为一个服务器。
反向代理的作用:
-
保证内网的安全,可以使用反向代理提供 WAF 功能,阻止 web 攻击大型网站,通常将反向代理作为公网访问地址,Web 服务器是内网。
-
负载均衡,通过反向代理服务器来优化网站的负载
这里比如有三台tomcat服务在 192.168.181.138 的物理服务器中,使用nginx实现反向代理和负载均衡的配置如下
#gzip on;
#nginx需要代理的三台tomcat主机,并实现负载均衡
upstream www.taozi.com{
#每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。
#ip_hash;
server 192.168.181.138:6060 max_fails=3 fail_timeout=3s weight=2;
server 192.168.181.138:7070;
server 192.168.181.138:8080;
}
server {
listen 80;
server_name www.taozi.com;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
# root html;
# index index0.html index.htm;
proxy_pass http://www.taozi.com;
}
}
这样当访问http://www.toazi.com的时候,会代理到192.168.181.138的三个tomcat服务中,其中weight值越大越有可能被分配到。
nginx默认的是以轮询机制进行负载均衡的