优秀的编程知识分享平台

网站首页 > 技术文章 正文

Nginx反向代理:通过外网访问内网数据库(mysql)

nanyue 2025-01-21 20:24:19 技术文章 5 ℃

Nginx反向代理:通过外网访问内网数据库

  • 前言
  • 项目场景:
  • 问题描述及分析:
  • 解决方案:
    • 1 在部署nginx里配置端口IP
    • 2 在外网nginx配置反向代理参数
    • 3 重启nginx

前言

部署nginx是基础,具体安装过程请参照这
NGINX链接:link

项目场景:

提示:这里简述项目相关背景:
例如:项目场景:示例:通过蓝牙芯片(HC-05)与手机 APP 通信,每隔 5s 传输一批传感器数据(不是很大)

问题描述及分析:

当不知道到内网后不可能直接通过内网访问数据库,而是反向代理给外网80端口映射出去,

解决方案:

分为两步,
1 在部署NGINX里配置端口IP
2 在外网nginx配置反向代理参数

1 在部署nginx里配置端口IP

  1. 找到cd 到文件位置
# 1 cd 到当前文件夹
cd /opt/newgopingtai/nginx 
# 2 编辑文件

	server
    {
        listen 1224;
        server_name 10.*.**.*;
        index index.html;
        root  /www/wwwroot/StarlightSchool/web/dist;  #dist上传的路径
       # 避免访问出现 404 错误
        location / {
          try_files $uri $uri/ @router;
          index  index.html;
        }
        location @router {
          rewrite ^.*$ /index.html last;
        }
	
    }
    # 注意这里主要是前端部署IP信息

2 在外网nginx配置反向代理参数

  1. 首先找到外网IP80端口
  2. 清楚自己匹配规则
    #优先级由高到低
    #location = /xxxx 精确匹配
    #location ^~ /cxxkjk 前缀匹配
    #location ~ pattern 分大小写的正则匹配
    #location ~* pattern 不分大小写的正则匹配
    #location /cxcxcx 前缀匹配(比带 ^~ 的前缀匹配优先级低)
    #location / 通用匹配
  3. 匹配内容


4. 保存conf文件

http {
 
	
	server{
		listen 80;
		root html;
		include mime.types;
        default_type application/octet-stream;	
				
		client_max_body_size    4000m;
		proxy_read_timeout 1200s;
        proxy_send_timeout 1200s;
		
		proxy_set_header Origin 127.0.0.1;
		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;
		
		
		
	
		#优先级由高到低
		#location = /xxxx    精确匹配
		#location ^~ /cxxkjk   前缀匹配
		#location ~ pattern  分大小写的正则匹配
		#location ~* pattern  不分大小写的正则匹配
		#location /cxcxcx    前缀匹配(比带 ^~ 的前缀匹配优先级低)
		#location /    通用匹配
	

		# 最优先的
		
		
		location ^~ /starlightleading/js {
			#root /www/wwwroot/StarlightSchool/web/dist/js;
			proxy_pass http://10.*.**.*:1224/js;
		}

		location ^~ /starlightleading/css {
			#root /www/wwwroot/StarlightSchool/web/dist/css;
			proxy_pass http://10.*.**.*:1224/css;
		}
		
		location ^~ /starlightleading/font {
			#root /www/wwwroot/StarlightSchool/web/dist/css;
			proxy_pass http://10.*.**.*1224/font;
		}
		
		# 星光学校前端转接URL
		location ^~ /starlightafter/ {
			proxy_pass http://10.*.**.*:1224/;
		}
		# 星光学校后端转接URL
		location  ^~ /starlightleading/ {
			proxy_pass http://10.*.**.*:1223/;
		}
		
	}

}

3 重启nginx

1 cd 配置文件目录
cd /opt/newgopingtai/nginx
2 重启nginx
docker-compose restart ng

访问外网IP

http://109..**.:107/starlightafter/
完美收工
觉得有帮助记得留下你的小星星

最近发表
标签列表