Nginx反向代理的一次使用总结

简介

高性能的HTTP和反向代理服务器

关键词

事件驱动 高效的反向代理、负载平衡 稳定 丰富的模块库 配置灵活 低资源占用

常用命令

假设运行环境为windows且nginx所在目录为D:\nginx-1.12.1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 启动服务(会有窗口一闪而过,可以正常访问`localhost:3000`则说明启动成功)
D:\nginx-1.12.1> start nginx

# 快速关闭Nginx,可能不保存相关信息,并迅速终止web服务
D:\nginx-1.12.1> nginx -s stop
# 平稳关闭Nginx,保存相关信息,有安排的结束web服务
D:\nginx-1.12.1> nginx -s quit
# 重新加载配置
D:\nginx-1.12.1> nginx -s reload
# 不运行,仅测试有效的配置文件
D:\nginx-1.12.1> nginx -t
# 显示 nginx 的版本
D:\nginx-1.12.1> nginx -v
# 显示 nginx 的版本,编译器版本和配置参数
D:\nginx-1.12.1> nginx -V

实际使用

使用反向代理来实现不同的域名访问同一台服务器上不同端口的web应用(隐藏端口号)

应对当同一服务器上,同时存在多种类型的web服务器时(比如同时存在部署在tomcat上的应用以及nodeJs应用),避免需要采用端口号来区分不同的web应用

核心配置文件为conf/nginx.conf,可以用nginx -c命令重新制定配置文件

  1. 为了尽量不污染原生配置,我们在conf目录下新建文件夹myConf,然后编辑conf/nginx.conf文件,在http配置末尾添加include myConf/*.conf;来导入我们自定义的配置文件。

  2. myConf中新建配置,如test.conf,填入配置信息如下:

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
38
39
upstream webServer01 {
server 127.0.0.1:3001;
keepalive 64;
}

upstream webServer02 {
server 127.0.0.1:3002;
keepalive 64;
}

server {
listen 80;
server_name www.myApp01.com;
#access_log /var/log/nginx/test.log;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Nginx-Proxy true;
proxy_set_header Connection "";
proxy_pass http://webServer01;

}

}

server {
listen 80;
server_name www.myApp02.com;
#access_log /var/log/nginx/test.log;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Nginx-Proxy true;
proxy_set_header Connection "";
proxy_pass http://webServer02;
}
}

修改配置文件后重新启动nginx服务,当我们以 www.myApp01.com 访问时,将进入webServer01,当我们以 www.myApp02.com 访问时,将进入webServer02,
当然,前提www.myApp01.comwww.myApp02.com都是指向你本机IP地址的有效域名