前言
nginx可以实现路由重写
nginx路由重写
准备接口
1package org.example.demoapi.controller; 2 3 4import org.springframework.web.bind.annotation.GetMapping; 5import org.springframework.web.bind.annotation.RequestMapping; 6import org.springframework.web.bind.annotation.RestController; 7 8@RestController 9@RequestMapping("/api/v2/user") 10public class UserController { 11 12 13 @GetMapping("/getUser") 14 public String getUser() { 15 return "User Controller"; 16 } 17} 18
端口为7000
路由重写
这个接口使用
1http://localhost:7000/api/v2/user/getUser 2
要使用
1http://localhost:7000/api/v1/user/getUser 2
nginx可以配置
1# ✅ 正确:两边都有尾部斜杠 2location /api/v1/ { 3 proxy_pass http://127.0.0.1:7000/api/v2/; 4} 5 6# ❌ 错误:缺少任一斜杠都会导致路径拼接而非替换 7location /api/v1/ { 8 proxy_pass http://127.0.0.1:7000/api/v2; # 会变成 /api/v2/api/v1/user/getUser 9} 10 11
或者使用
1 server { 2 listen 80; 3 server_name localhost; 4 5 access_log d:/temp/access.log req_format; 6 7 location / { 8 # 仅重写 /api/v1/ 开头的路径,保留后续部分 9 rewrite ^/api/v1/(.*)$ /api/v2/$1 break; 10 11 proxy_pass http://127.0.0.1:7000; 12 proxy_set_header Host $host; 13 proxy_set_header X-Real-IP $remote_addr; 14 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 15} 16
总结
使用nginx可以路由重写或者转发