nginx

Nginx 的使用

Nginx 是一个高性能的 HTTP 和反向代理 Web 服务器

核心:反向代理、负载均衡、动静分离

加权策略

  1. 轮询:将请求轮着发给每一台服务器
  2. 加权轮询:在轮询的基础上加上权重值

Nginx常用命令

1
2
3
4
5
6
cd /usr/local/nginx/sbin/
./nginx #启动
./nginx -s stop # 停止
./nginx -s quit #安全退出
./nginx -s reload # 重新加载配置文件
ps aux|grep nginx # 查看nginx进程

配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
worker_processes  1;
# 全局配置
events {
worker_connections 1024;
}

# http配置
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;

upstream hqzqaq{
# 负载均衡配置
# 服务器资源
server 127.0.0.1:8080 weight=1;
server 127.0.0.1:8081 weight=1;
}

server {
listen 81;
server_name localhost;
# 反向代理
location /{
root html;
index index.html index.htm;
proxy_pass http://hqzqaq;
}
}
server {
listen 443;
server_name localhost;
# 代理
}
}

1、1. 反向代理

打开浏览器,在地址栏输入地址 www.123.com,跳转到 linux 系统 tomcat 主页面中

1
2
3
4
5
6
7
8
9
server{
listen 80;
server_name 服务器地址
location / { # /表示路径中包含 /
root html;
proxy_pass http://127.0.0.1:8080; # 访问服务器的80端口时,将请求转发到本地的8080端口
index index.html index.htm;
}
}

使用 nginx 反向代理,根据访问的路径跳转到不同端口的服务器中

1
2
3
4
5
6
7
8
9
10
server{
listen 9001;
server_name 服务器地址;
location ~ /edu/{
proxy_pass http://127.0.0.1:8080;
}
location ~ /vod/{
proxy_pass http://127.0.0.1:8081;
}
}

2、2. 负载均衡

浏览器地址栏输入地址 http://192.168.17.129/edu/a.html 负载均衡效果,将请求平均到 8080 和 8081 端口中

1
2
3
4
5
6
7
8
9
10
11
upstream myserver{
ip_hash;
server 服务器地址:8080 weight=1;
server 服务器地址:8180 weight=1;
}
server{
location / {
proxy_pass http://myserver;
proxy_connect_timeout 10;
}
}

3、3. 动静分离

将动态请求和静态请求分开,可以理解为 nginx 处理静态页面, tomcat 处理动态页面。

1
2
3
4
5
6
7
8
9
10
11
12
server{
listen 80;
server_name 服务器地址;
location /www/ {
root 静态资源路径;
index index.html index.htm;
}
location /image/ {
root 静态资源路径;
autoindex on;
}
}
  • Copyrights © 2022-2023 hqz

请我喝杯咖啡吧~

支付宝
微信