用Nginx做端口转发(反向代理)
有时我们会使用一些java或node应用,但又不想让他们直接监听80端口,这时就需要用到端口转发
本文中,我们介绍Nginx如何做端口转发,还有各种转发规则
将域名转发到本地端口
首先介绍最常用的,将域名转发到本地另一个端口上
server{ listen 80; server_name tomcat.shaochenfeng.com; index index.php index.html index.htm; location / { proxy_pass http://127.0.0.1:8080; # 转发规则 proxy_set_header Host $proxy_host; # 修改转发请求头,让8080端口的应用可以受到真实的请求 proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
这样访问 http://tomcat.shaochenfeng.com 时就会转发到本地的 8080 端口
将域名转发到另一个域名
server{ listen 80; server_name baidu.shaochenfeng.com; index index.php index.html index.htm; location / { proxy_pass http://www.baidu.com; proxy_set_header Host $proxy_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
本地一个端口转发到另一个端口或另一个域名
server{ listen 80; server_name 127.0.0.1; # 公网ip index index.php index.html index.htm; location / { proxy_pass http://127.0.0.1:8080; # 或 http://www.baidu.com proxy_set_header Host $proxy_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
加 / 与不加 /
在配置proxy_pass代理转发时,如果后面的url加/,表示绝对根路径;如果没有/,表示相对路径
例如
加 /
server_name shaochenfeng.com location /data/ { proxy_pass http://127.0.0.1/; }
访问 http://shaochenfeng.com/data/index.html 会转发到 http://127.0.0.1/index.html
不加 /
server_name shaochenfeng.com location /data/ { proxy_pass http://127.0.0.1; }
访问 http://shaochenfeng.com/data/index.html 会转发到 http://127.0.0.1/data/index.html
分类:
nginx
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~