Termux中使用Nginx反向代理

项目背景:在 Termux 中运行了多个 web 项目,但是只有一个域名。这种情况下可以使用 Nginx 反向代理将不同访问路径映射到不同的项目。比如访问 itfox.net/express/ 会映射到 8080 端口的 express 项目,而访问 itfox.net 会映射 3000 端口的到默认项目。

安装 Nginx

1
2
3
4
5
# 安装 nginx
$ pkg install nginx

# 启动 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
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# /data/data/com.termux/files/usr/etc/nginx/nginx.conf

#user nobody;
worker_processes 1;

#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

#pid logs/nginx.pid;


events {
worker_connections 1024;
}


http {
include mime.types;
default_type application/octet-stream;

#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';

#access_log logs/access.log main;

sendfile on;
#tcp_nopush on;

#keepalive_timeout 0;
keepalive_timeout 65;

#gzip on;

server {
listen 8088;
server_name *.itfox.net localhost;

#charset koi8-r;

#access_log logs/host.access.log main;

# location / {
# root /data/data/com.termux/files/usr/share/nginx/html;
# index index.html index.htm;
# }

location ~ /express/ {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location / {
proxy_pass http://127.0.0.1:3000;

# 反向代理获取真实 IP 地址
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

# websocket 反向代理
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}

#error_page 404 /404.html;

# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /data/data/com.termux/files/usr/share/nginx/html;
}
}

# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;

# location / {
# root html;
# index index.html index.htm;
# }
#}
}

参考资料
nginx 反向代理+路径重写 配置
nginx 配置文件 nginx.conf 之 server 及 server_name 的意义详解

重启 Nginx

1
2
3
4
5
6
# 重新加载配置文件
$ nginx -s reload

# 或者:先关闭再运行
$ nginx -s stop
$ nginx

最后,配合内网穿透就可以使用域名访问项目了。


Termux中使用Nginx反向代理
https://blog.itfox.net/posts/termux中使用nginx反向代理.html
作者
blog.itfox.net
发布于
2023年1月22日
许可协议