nginx路由重写

24 阅读1分钟

前言

nginx可以实现路由重写

nginx路由重写

准备接口

package org.example.demoapi.controller;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v2/user")
public class UserController {


    @GetMapping("/getUser")
    public String getUser() {
        return "User Controller";
    }
}

端口为7000

路由重写

这个接口使用

http://localhost:7000/api/v2/user/getUser

要使用

http://localhost:7000/api/v1/user/getUser

nginx可以配置

# ✅ 正确:两边都有尾部斜杠
location /api/v1/ {
    proxy_pass http://127.0.0.1:7000/api/v2/;
}

# ❌ 错误:缺少任一斜杠都会导致路径拼接而非替换
location /api/v1/ {
    proxy_pass http://127.0.0.1:7000/api/v2;  # 会变成 /api/v2/api/v1/user/getUser
}

或者使用

 server {
        listen       80;
        server_name  localhost;

        access_log  d:/temp/access.log  req_format;
		
		location / {
    # 仅重写 /api/v1/ 开头的路径,保留后续部分
    rewrite ^/api/v1/(.*)$ /api/v2/$1 break;
    
    proxy_pass http://127.0.0.1:7000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

总结

使用nginx可以路由重写或者转发