nginx 主要应用场景
1、反向代理
关键命令: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、负载均衡
关键命令: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服务器
关键命令:root 当只有静态资源的时候,就可以使用Nginx来做服务器
server {
listen 80;
server_name localhost;
location / {
root /www/data;
index index.html;
}
}
4、正向代理 不支持HTTPS