nginx
nginx是高性能的http和反向代理服务器,特点占用内存少,并发能力强
nginx是一个跨平台服务器,可以运行在Linux, Mac Os, windows等操作系统
- 正向代理:客户端的多个请求到代理服务器,代理服务器将其转发到目标服务器,然后将目标服务器生成的响应返回给客户端。
- 反向代理:代理服务器接受到多个请求,将其分配转发到多个服务器,然后将响应返回给客户端。
- 负载均衡:将原来请求集中到单个服务器的情况改为请求分发到多个服务器。
- 动静分离:把动态页面和静态页面交给不同的服务器来解析,加快解析的速度,降低由单个服务器的压力。
启动nginx
// 进入nginx解压目录
start nginx
关闭nginx
// 完整有序停止nginx(推荐)
nginx -s quit
// 快速停止nginx
nginx -s stop
重启nginx
nginx -s reload
nginx配置
events
- 影响nginx服务器与用户的网络连接
events {
# 支持的最大连接数
worker_connections 1024;
}
location指令说明
location[ = | ~ | ~* | ^~] url{
}
- =:用于不含正则表达式的url前,要求字符串与url严格匹配,匹配成功就停止向下搜索并处理请求
- ~:用于表示url包含正则表达式,并且区分大小写
- ~*:用于表示url包含正则表达式,并且不区分大小写
- ^~:用于不含正则表达式的url前,要求nginx服务器找到表示url和字符串匹配度最高的location后,立即使用此location处理请求,而不再匹配
- 如果有url包含正则表达式,不需要有~开头标识
nginx配置静态资源(动静分离)
- 前端项目可开启静态服务器
- 静态资源开启静态服务器
server {
listen 9000;
server_name localhost;
root D:/projects/myproject; # 根路径
location / { # 静态资源
root /
index index.html index.htm
}
# 访问 localhost:9000/images/ 下的静态文件指向D:/projects/myproject/images/
location /images/ { # 静态资源
root /images/; #root后面的路径是从根路径root开始
autoindex on;
}
location ^~ /api/ { # 动态资源
proxy_pass http://eap_website/api/;
}
}
nginx配置反向代理
# 访问 http:/localhost:9000/ed1/ 代理转发到 http:/localhost:8081/
# 访问 http:/localhost:9000/ed2/ 代理转发到 http:/localhost:8082/
# 代理服务器
server {
listen 9000;
server_name localhost;
location /ed1/ {
root html;
proxy_pass http://localhost:8081; # proxy_pass 转发
}
location /ed2/ {
root html;
proxy_pass http://localhost:8082;
}
}
# 目标服务器1
server {
listen 8081;
server_name localhost;
root D:/projects/project1;
location / {
root html;
index index.html index.htm;
}
}
# 目标服务器2
server {
listen 8082;
server_name localhost;
root D:/projects/project2;
location / {
root html;
index index.html index.htm;
}
}
nginx配置负载均衡
- 轮询(默认)
- weight,代表权,权越高优先级越高
- fair,按后端服务器的响应时间来分配请求,相应时间短的优先分配
- ip_hash,每个请求按照访问ip的hash结果分配,这样每一个访客固定的访问一个后端服务器,可以解决session 的问题
# 负载均衡
upstream myserver {
ip_hash;
server http://localhost:8081 weight=1;
server http://localhost:8082 weight=2;
fair;
}
# 代理服务器
server {
listen 9000;
server_name localhost;
location / {
root html;
index index.html index.htm;
proxy_pass http://myserver;
}
}