0%

nginx反向代理

当只有一台服务器,而又想运行多个 web 后端服务,且希望网址为 www.XX.com / bbs.XX.com / blog.XX.com,怎么办,此时就要用nginx进行反向代理

以 ubuntu 为例

  1. 安装 NGINX
1
$ sudo apt-get install nginx
  1. 修改 NGINX 的配置文件
    1
    2
    # 配置文件在 /etc/nginx/nginx.conf
    cd /etc/nginx
    然后修改 nginx.conf,
    具体为:修改配置文件中 的 http{}
    在 http{} 中的末尾补上反向代理配置代码
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
user www-data;
worker_processes auto;
pid /run/nginx.pid;
events {
worker_connections 768;
# multi_accept on;
}
http {
##
# 前面的代码再此不展示了,在 http{} 中补上以上代码
##
##
# 反向代理配置代码
##
# 注意端口号 8081 为 bbs 服务, 8082 为 blog 服务,8083 为 www 服务
upstream bbs {
server 127.0.0.1:8081 weight=1;
}
upstream blog {
server 127.0.0.1:8082 weight=1;
}
upstream www {
server 127.0.0.1:8083 weight=1;
}
server{
listen 80;
# 配置 www.bigbananas.cn
server_name www.bigbananas.cn;
access_log /var/log/nginx/www.log;
location / {
root /home/website_root;
}
}
server{
listen 80;
# 配置 blog.bigbananas.cn
server_name blog.bigbananas.cn;
access_log /var/log/nginx/blog_access.log;
location / {
root /home/todo_root;
# proxy_pass 为反向代理后的 网站
proxy_pass http://127.0.0.1:8081/;
proxy_read_timeout 300;
proxy_connect_timeout 300;
proxy_redirect off;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
}
}
server{
listen 80;
# 配置 bbs.bigbananas.cn
server_name bbs.bigbananas.cn;
access_log /var/log/nginx/bbs_access.log;
location / {
root /home/todo_root;
# proxy_pass 为反向代理后的 网站
proxy_pass http://127.0.0.1:8082/;
proxy_read_timeout 300;
proxy_connect_timeout 300;
proxy_redirect off;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
}
}
}

3、 在重启 NGINX 服务

1
$ sudo nginx -s reload

4、 在服务器启动 BLOG、BBS、WWW 服务

注意:
端口号 8081 为 bbs 服务, 8082 为 blog 服务,8083 为 www 服务