nginx:把uri中的/api删去,然后剩余部分(包括?a=b这样的请求参数)转发给tomcat该怎么写?

我想要针对所有向 wangzhan.com/api/{something} 发起的请求,然后把它变成 wangzhan.com/{something} (也就是说把 /api 给去掉) 发给监听 8080 端口的 tomcat 该如何做呢?

我自己原来写的如下,但是这个有大问题,它会丢失?a=b这个参数部分

    server {
        listen  80 default_server;
        server_name 这行没啥问题,自己小破站的网址就不贴了

        if ( $request_uri !~ ^/api/.*$ ){
            rewrite ^/(.*)$ https://$server_name/$1 permanent;
        }

        location ~ ^/api/(.*)$ {
            echo $1; #为什么能用 echo ?因为我安装了 echo-nginx-module 这个模块
            # proxy_pass http://127.0.0.1:8080/$1; 这个是我原来写的,后来我觉得哪里不对于是用 echo 进行测试,才注释掉了这一行有了上面一行
        }
    }

使用echo进行测试后,结果如下

root@VM-133-145-debian:~# curl localhost/api/hello
hello
root@VM-133-145-debian:~# curl localhost/api/hello?a=b
hello

不知道为什么会这样,我也很绝望。。

阅读 3.7k
1 个回答

把这个 $is_args$args 拼在后面去

  • $is_args
    当有 $args (和$query_string一样) 时,此处为 ? 否则为空
  • $args
    $query_string 一致,表查询字符串即,GET 参数
location ~ ^/api/(.*)$ {
    proxy_pass http://127.0.0.1:8080/$1$is_args$args
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题