Nginx安装
1、去官网http://nginx.org/下载对应的nginx包,推荐使用稳定版本
2、上传nginx到linux系统
3、安装依赖环境
(1) 安装gcc环境
yum install gcc-c++
(2) 安装PCRE库,用于解析正则表达式
yum install -y pcre pcre-devel
(3) zlib压缩和解压缩依赖
yum install -y zlib zlib-devel
(4) SSL 安全的加密的套接字协议层,用于HTTP安全传输,也就是https
yum install -y openssl openssl-devel
4、安装ngnix
tar -zxvf nginx-1.20.2.tar.gz //解压
//进入解压缩目录,执行./configure后。
make && make install //安装
5、启动
//进入 nginx/sbin 目录
./nginx //启动
./nginx -s stop //停止
./nginx -s reload //重新加载
注: 端口号开放
反向代理
配置server
server {
listem 80;
server_name localhost;
location / {
proxy_pass http://127.0.0.1:8080;
index index.html index.htm;
}
}
负载均衡
1、配置负载均衡服务器列表,默认采用轮询的方式
//每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器 down 掉,则自动剔除
upstream [proxyName] {
server 192.168.1.2:8080;
server 192.168.1.3:8080;
server 192.168.1.4:8080;
}
配置server
server {
listem 80;
server_name localhost;
location / {
proxy_pass http://[proxyName];
index index.html index.htm;
}
}
2、加权轮询
//weight 代表权重,默认为 1,权重越高被分配的客户端越多
upstream [proxyName] {
server 192.168.1.2:8080 weight=1;
server 192.168.1.3:8080 weight=1;
server 192.168.1.4:8080 weight=1;
}
3、ip_hash分配
//每个请求按访问 ip 的 hash 结果分配,这样每个访客固定访问一个后端服务器,可以解决 session 的问题
upstream [proxyName] {
ip_hash;
server 192.168.1.2:8080;
server 192.168.1.3:8080;
server 192.168.1.4:8080;
}
4、fair分配 (第三方)
//按后端服务器的响应时间来分配请求,响应时间短的优先分配
upstream [proxyName] {
server 192.168.1.2:8080;
server 192.168.1.3:8080;
server 192.168.1.4:8080;
faiir;
}
动静分离
配置server
server {
listem 80;
server_name localhost;
location /www/ {
root /www/;
index index.html index.htm;
}
location /api/ {
root /api/;
index index.html index.htm;
}
}
keepalived高可用集群
LVS(Linux Virtual Server)实现高可用负载均衡
搭建Keepalived+Lvs+Nginx高可用集群负载均衡
注释
端口号开放
//查看开放的端口号
firewall-cmd --list-all
//设置开放的端口号
firewall-cmd --add-service=http --permanent
sudo firewall-cmd --add-port=80/tcp --permanent
//重启防火墙
firewall-cmd --reload
配置文件
nginx/conf/nginx.conf
location指令说明
location [ = | ~ | ~* | ^~ ] uri {
}
1、= :用于不含正则表达式的 uri 前,要求请求字符串与 uri 严格匹配,如果匹配成功,就停止继续向下搜索并立即处理该请求。
2、~:用于表示 uri 包含正则表达式,并且区分大小写。
3、~*:用于表示 uri 包含正则表达式,并且不区分大小写。
4、^~:用于不含正则表达式的 uri 前,要求 Nginx 服务器找到标识 uri 和请求字符串匹配度最高的 location 后,立即使用此 location 处理请求,而不再使用 location 块中的正则 uri 和请求字符串做匹配。
注意:如果 uri 包含正则表达式,则必须要有 ~ 或者 ~* 标识。