如何从没有运算符的Nginx位置捕获变量

时间:2018-08-26 19:09:30

标签: nginx nginx-location

在这里是URL,其中没有欢迎词并选择了主页。

location ~* "^\/(?!\b(welcome|home)\b)[^\/\.]*$" {
    proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504 http_404;
    proxy_redirect off;
    proxy_read_timeout 180;
    proxy_set_header Host $host ;
    proxy_set_header X-Real-IP $remote_addr ;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for ;
    proxy_pass http://127.0.0.1:3000/custom-pages/$1$is_args$args;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

我想在$ 1变量中传递该子弹。

1 个答案:

答案 0 :(得分:1)

您可以使用$uri来获取 @Richard 所建议的完整URL,但是如果您的位置稍微复杂一些,例如/my-directory/<<slug>>,则$uri达不到您的目的。

在这种情况下,您可以轻松地将捕获组用作([^\/\.]*)并将其保存在$2中:

location ~* "^\/my-directory\/(?!\b(welcome|home)\b)([^\/\.]*)$" {
    ...

    proxy_pass http://127.0.0.1:3000/custom-pages/$2$is_args$args;

    ...
}

此外,您的否定前瞻(?!\b(welcome|home)\b)将丢弃所有以欢迎开头的位置,例如/welcome-here或{{1} }。

因此,为了能够捕获它们并仅丢弃/home-is-where-u-r/home,您只需将其更改为/welcome