nginx RegEx在位置 - 获取单个字母

时间:2015-11-25 14:02:22

标签: nginx

我想要捕获一个位置并将前5个字母作为位置块中的变量,这样我就可以构建一个新路径。

例如:

location /direct/(.)(.)(.)(.)(.)(.*) {
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_pass http://localhost:1234/$1$2$3$4$5$6; }

我该怎么做?

2 个答案:

答案 0 :(得分:0)

使用类似

的内容
location ~ "/direct/(?<myvar>.{5})(?<other_var>.*)" { use $myvar here }

答案 1 :(得分:0)

您可以匹配前5个字符并将其传递为$1

location ~ "^/direct/([\w]{5})(.*)" {
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_http_version 1.1;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $host;
    proxy_pass http://localhost:1234/$1;
}

这只会传递前5个字符,因此http://example.com/12345abcdefg将传递给http://example.com:1234/12345,从而删除原始URI中剩余的“abcdefg”