正则表达式截断 nginx 上的字符串

标签 regex nginx caching

我正在尝试使用 nginx 缓存功能,但是我们有使用纬度和经度的端点,因此为了提高缓存命中率,我们必须截断纬度和经度。

我创建了一个忽略最后两个纬度数字的 map 。问题是 map 不工作,它总是返回原始纬度 (45.45452)。

考虑 $arg_latitude 为 45.45452,预期结果为 45.45。

map $arg_latitude $rounded_latitude {
    default $arg_latitude;
    ~\d+\.\d\d $arg_latitude;
}

知道为什么不起作用吗?

最佳答案

map 的结果始终是 $arg_latitude 的原始值,因为这是您在右侧列中插入的值。

您需要向正则表达式添加捕获并将其用作新值。

例如:

map $arg_latitude $rounded_latitude {
    default                 $arg_latitude;
    ~^(?<rounded>\d+\.\d\d) $rounded;
}

建议使用命名捕获,因为在评估 $rounded_latitude 时,数字捕获可能不在范围内。

参见 this document了解更多。

关于正则表达式截断 nginx 上的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52487959/

相关文章:

php - AWS ECS Docker-nginx : [emerg] host not found in upstream

php - 通过 ssl 下载非常慢的 Nginx

javascript - jQuery.getJSON : how to avoid requesting the json-file on every refresh?(缓存)

java - 用一个字符替换任何数字序列

c# - 正则表达式搜索单个 0 并添加逗号

ruby-on-rails - 通过 Nginx 代理时使用 OmniAuth 时出现 CallbackError

caching - 在数据库和 redis 缓存之间同步数据的最佳策略是什么

java - HashMap用作Cache时的性能问题

regex - 在正则表达式中遍历字符串两次

Javascript 正则表达式用特殊字符替换字符串