
博客目录
-
- 方法 1:使用 rewrite 指令
- 方法 2:使用 location 代理
- 方法 3:精确的路径重写
- 完整的 nginx 配置示例
- 配置说明:
- 测试配置:
需求:
http://127.0.0.1/test-chat/orig\_docs/80a4e16a-6945-4fa0-bc8a-2b9c9c6eacb7
使用 nginx 转为下面的请求
http://127.0.0.1/orig\_docs/80a4e16a-6945-4fa0-bc8a-2b9c9c6eacb7
可以使用 nginx 的rewrite或location指令来实现这个 URL 转换。以下是几种配置方式:

方法 1:使用 rewrite 指令
1server { 2 listen 80; 3 server_name 127.0.0.1; 4 5 # 方法1.1:在server级别重写 6 rewrite ^/test-chat/orig_docs/(.*)$ /orig_docs/$1 permanent; 7 8 # 或者方法1.2:在location中重写 9 location /test-chat/orig_docs/ { 10 rewrite ^/test-chat/orig_docs/(.*)$ /orig_docs/$1 permanent; 11 } 12} 13
方法 2:使用 location 代理
1server { 2 listen 80; 3 server_name 127.0.0.1; 4 5 location /test-chat/orig_docs/ { 6 # 移除test-chat前缀 7 rewrite ^/test-chat(/orig_docs/.*)$ $1 break; 8 9 # 代理到实际服务 10 proxy_pass http://your_backend_server; 11 proxy_set_header Host $host; 12 proxy_set_header X-Real-IP $remote_addr; 13 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 14 proxy_set_header X-Forwarded-Proto $scheme; 15 } 16 17 location /orig_docs/ { 18 # 处理原始/orig_docs请求 19 proxy_pass http://your_backend_server; 20 proxy_set_header Host $host; 21 proxy_set_header X-Real-IP $remote_addr; 22 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 23 proxy_set_header X-Forwarded-Proto $scheme; 24 } 25} 26
方法 3:精确的路径重写
1server { 2 listen 80; 3 server_name 127.0.0.1; 4 5 location ~ ^/test-chat/orig_docs/(.+)$ { 6 return 301 /orig_docs/$1; 7 } 8} 9
完整的 nginx 配置示例
1server { 2 listen 80; 3 server_name 127.0.0.1; 4 5 # 访问日志 6 access_log /var/log/nginx/access.log; 7 error_log /var/log/nginx/error.log; 8 9 # 重写规则:移除test-chat前缀 10 rewrite ^/test-chat/orig_docs/(.*)$ /orig_docs/$1 permanent; 11 12 # 处理/orig_docs请求 13 location /orig_docs/ { 14 # 这里配置您的后端服务 15 proxy_pass http://backend_server; 16 proxy_set_header Host $host; 17 proxy_set_header X-Real-IP $remote_addr; 18 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 19 proxy_set_header X-Forwarded-Proto $scheme; 20 21 # 可选:设置超时时间 22 proxy_connect_timeout 30s; 23 proxy_send_timeout 30s; 24 proxy_read_timeout 30s; 25 } 26 27 # 其他location配置... 28 location / { 29 # 默认处理 30 root /usr/share/nginx/html; 31 index index.html; 32 } 33} 34
配置说明:
permanent(301 重定向):浏览器会记住重定向,适合永久性 URL 变更redirect(302 重定向):临时重定向,每次都会请求原 URLbreak:在 server 内部重写,不对外部重定向
测试配置:
1# 检查nginx配置语法 2nginx -t 3 4# 重新加载配置 5nginx -s reload 6
选择哪种方法取决于您的具体需求:
- 如果希望用户浏览器地址栏显示新的 URL,使用
permanent或redirect - 如果只是内部重写,使用
break - 如果需要代理到其他服务,使用方法 2 的代理配置
觉得有用的话点个赞
👍🏻呗。
❤️❤️❤️本人水平有限,如有纰漏,欢迎各位大佬评论批评指正!😄😄😄💘💘💘如果觉得这篇文对你有帮助的话,也请给个点赞、收藏下吧,非常感谢!👍 👍 👍
🔥🔥🔥Stay Hungry Stay Foolish 道阻且长,行则将至,让我们一起加油吧!🌙🌙🌙
《【Nginx系列】前端重定向》 是转载文章,点击查看原文。