nginx 主要应用场景
1、反向代理
![](https://img2018.cnblogs.com/blog/1158536/201911/1158536-20191127160755228-988235408.png)
关键命令:proxy_pass;如将 localhost 的80端口 转到 localhost 8080端口
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://localhost:8080;
proxy_set_header Host $host:$server_port;
}
}
2、负载均衡
负载均衡也是Nginx常用的一个功能,简单而言就是当有2台或2台以上服务器时,根据规则随机的将请求分发到指定的服务器上处理,负载均衡配置一般都需要同时配置反向代理,通过反向代理跳转到负载均衡。而Nginx目前支持自带3种负载均衡策略,还有2种常用的第三方策略
关键命令:upstream;如将localhost 80端口的请求 均分到 localhost 8080 和 localhost 8081两个服务上
负载方案:
1)、权重 weight:必须实现session 共享,否则导致用户session不同步,导致用户重新登陆
upstream test {
server localhost:8080 weight=9; #请求的 90% 进入到8080服务器
server localhost:8081 weight=1; #请求的 10% 进入到8081服务器
}
2)、ip_hash:每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题
upstream test {
ip_hash;
server localhost:8080;
server localhost:8081;
}
3)、fair(第三方):按后端服务器的响应时间来分配请求,响应时间短的优先分配。
upstream test {
fair;
server localhost:8080;
server localhost:8081;
}
4)、url_hash(第三方):问url的hash结果来分配请求,使每个url定向到同一个后端服务器,后端服务器为缓存时比较有效
upstream backend {
hash $request_uri;
hash_method crc32;
server localhost:8080;
server localhost:8081;
}
5)、默认:按照时间一次分配到不同的机器上
upstream test {
server localhost:8080;
server localhost:8081;
}
server {
listen 80;
server_name localhost;
client_max_body_size 1024M;
location / {
proxy_pass http://test;
proxy_set_header Host $host:$server_port;
}
}
3、WEB服务器
Nginx本身也是一个静态资源的服务器,当只有静态资源的时候,就可以使用Nginx来做服务器,同时现在也很流行动静分离,就可以通过Nginx来实现,首先看看Nginx做静态资源服务器
这样如果访问 http://localhost 就会默认访问到 E://www/data
目录下面的index.html
,如果一个网站只是静态页面的话,那么就可以通过这种方式来实现部署
关键命令:root 当只有静态资源的时候,就可以使用Nginx来做服务器
server {
listen 80;
server_name localhost;
location / {
root e:/www/data;
index index.html;
}
}
4、正向代理 不支持HTTPS
5、静态分离
upstream test{ server localhost:8080; server localhost:8081; } server { listen 80; server_name localhost; location / { root e:/wwwroot; index index.html; } # 所有静态请求都由nginx处理,存放目录为html location ~ .(gif|jpg|jpeg|png|bmp|swf|css|js)$ { root e:/wwwroot; } # 所有动态请求都转发给tomcat处理 location ~ .(do)$ { proxy_pass http://test; } error_page 500 502 503 504 /50x.html; location = /50x.html { root e:/wwwroot; } }