一、Nginx相关概念
1、反向代理
反向代理(Reverse Proxy)方式是指以代理服务器来接受internet上的连接请求,然后将请求转发给内部网络上的服务器,
并将从服务器上得到的结果返回给internet上请求连接的客户端,此时代理服务器对外就表现为一个服务器。
2、负载均衡
负载均衡,英文名称为Load Balance,是指建立在现有网络结构之上,并提供了一种廉价有效透明的方法扩展网络设备和服务器的带宽、
增加吞吐量、加强网络数据处理能力、提高网络的灵活性和可用性。其原理就是数据流量分摊到多个服务器上执行,减轻每台服务器的压力,
多台服务器共同完成工作任务,从而提高了数据的吞吐量。
二、Nginx的安装
1、下载
①、所有版本下载列表地址:http://nginx.org/download/
②、本次安装版本是:nginx-1.9.10
2、上传并解压Nginx
①、上传不多讲
②、解压执行命令
[root@localhost nginx]# tar -zxvf nginx-1.9.10.tar.gz
3、编译nginx
①、进入到nginx源码目录
[root@localhost nginx]# cd nginx-1.9.10/
②、检查安装环境,并指定将来要安装的路径
[root@localhost nginx-1.9.10]# ./configure --prefix=/usr/nginx
注意(重要):此命令可能会报一些错误
比如:./configure: error: C compiler cc is not found 则需要用yum安装 gcc
总结可能需要安装的包:
yum -y install gcc pcre-devel zlib-devel openssl openssl-devel
③、编译安装
[root@localhost nginx-1.9.10]# make&&make install
4、启动nginx
[root@localhost nginx-1.9.10]# /usr/nginx/sbin/nginx
5、查看端口是否有
ngnix进程监听(nginx默认监听是80)
[root@localhost nginx-1.9.10]# netstat -ntlp|grep 80
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 3837/nginx
[root@localhost nginx-1.9.10]#
三、配置Nginx(单)
①、备份配置文件nginx.conf(重要)
[root@localhost nginx]# cp conf/nginx.conf conf/nginx_bak.conf
[root@localhost nginx]#
②、编辑配置文件nginx.conf
server {
listen 80; #nginx所在服务器的主机端口
server_name localhost; #nginx所在服务器的主机名
#charset koi8-r;
#access_log logs/host.access.log main;
location / { #/表示拦截所有请求
proxy_pass http://192.168.126.101:81; #这里是代理走向的目标WEB服务器:tomcat,httpd等
}
③、开放nginx端口
[root@localhost nginx]# /sbin/iptables -I INPUT -p tcp --dport 80 -j ACCEPT
[root@localhost nginx]# /etc/rc.d/init.d/iptables save
iptables:将防火墙规则保存到 /etc/sysconfig/iptables: [确定]
[root@localhost nginx]# /etc/init.d/iptables restart
iptables:将链设置为政策 ACCEPT:filter [确定]
iptables:清除防火墙规则: [确定]
iptables:正在卸载模块: [确定]
iptables:应用防火墙规则: [确定]
[root@localhost nginx]#
④、启动nginx
[root@localhost nginx]# ./sbin/nginx
⑤、测试访问nginx服务器是否能访问到目标服务器
四、配置nginx代理多台(动静分离)
①、编辑配置文件nginx.conf
说明在两台被代理服务器上没有项目,所以用htm来充当动态url
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location ~ .*\.(html|js|css|gif|jpg|jpeg|png)$ { #静态
proxy_pass http://192.168.126.101:81;
}
location ~ .*\.(htm|jsp|do|action)$ { #动态
proxy_pass http://192.168.126.102:80;
}
②、重新启动nginx
[root@localhost nginx]# ps -ef|grep nginx
root 1194 1 0 17:42 ? 00:00:00 nginx: master process sbin/nginx
nobody 1195 1194 0 17:42 ? 00:00:00 nginx: worker process
root 1306 1158 0 18:20 pts/0 00:00:00 grep nginx
[root@localhost nginx]# kill -9 1194 1195
[root@localhost nginx]# sbin/nginx
[root@localhost nginx]#
③、测试nginx:输入nginx服务 如:
http://192.168.126.100/index.htm 和 http://192.168.126.100/index.html