【问题标题】:How to rewrite the URL in Nginx Regex and debug?如何在 Nginx Regex 中重写 URL 并进行调试?
【发布时间】:2022-01-24 05:29:01
【问题描述】:

我正在尝试从请求 URL 中删除 /api/v1 并简单地传递其余部分。例如 /api/v1/test/ 就是 /test。 /api/v1/test/ready 和 /test/ready 一样简单。

这是我尝试过的。我在想第一个参数,即 $1 将在 ^(/api/v1) 中捕获,其余部分将被捕获 (.*?)。 所以,我只是通过 $2 并打破它。但是,它不起作用。我不确定我做错了什么。我尝试了一些调试,但没有这样做。

location /api/v1 {
      rewrite ^(/api/v1)(.*?) $2; break;
      # tried return 200 $2;
      # but this will never hit since it is rewriting 
      # the rules will be evaluated again.
      # I guess break will not allow it to re run again for the rules.
      include uwsgi_params;
      uwsgi_pass 10.0.2.15:3031;
    }

我试图调试它,但我不能。 它从来没有命中位置/。例如。

location / {
             return 200 $request_uri;
      }

【问题讨论】:

  • 字符串的其余部分不能用惰性模式匹配,将(.*?)替换为(.*)
  • 另外,在$2break 之间有一个虚假的;

标签: regex nginx wsgi


【解决方案1】:

最后,我发现了问题所在。这是我的解决方案。 我认为找出问题所在的明显方法是在启用重定向日志之后 -

error_log /var/log/nginx/error.log notice;
 rewrite_log on;

这是位置上下文。

location /api/v1 {

            # uncomment the below two lines to see the redirection.
            # the re-direction happens from  /api/v1/ to /
            # error_log /var/log/nginx/error.log notice;
            # rewrite_log on;
            rewrite ^(/api/v1)(.*)/$ https://$host$2 break;
            
        }

        location / {
            uwsgi_pass unix:///tmp/sb_web_wsgi.sock;
            include uwsgi_params;
        }

【讨论】:

    猜你喜欢
    • 2019-01-24
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 2010-11-05
    • 2010-10-06
    相关资源
    最近更新 更多