我需要确保给定站点上的所有永久链接都以尾部斜杠结尾。也就是说,任何指向与实际的单个文件不对应的位置的 URL。我还需要保留与 URL 一起传递的任何查询字符串和/或 anchor 。
例子
假设我在以下位置有一个页面:
example.com/about/
如果我收到以下请求,我希望它们按所示重写:
example.com/about
>example.com/about/
example.com/about?src=fb
>example.com/about/?src=fb
example.com/about#contact
>example.com/about/#contact
example.com/about#contact?src=fb
>example.com/about/#contact?src=fb
但是,我想确保我不会重写任何实际文件路径 - 任何带有文件扩展名的路径。
到目前为止我有什么
这是我到目前为止想出的正则表达式,它只处理不包括真实文件路径的地址,并在字符串末尾没有斜杠时添加尾部斜杠:
^([^\.]*$(?<!\/))
我还没有弄清楚如何在存在 anchor 或查询字符串时确定尾部斜杠是否存在,一旦确定如何分别捕获尾部斜杠之前和之后的部分为了组装最终的重写。
最佳答案
事实证明,我想出的正则表达式确实满足了我所有的重写需求。这是我的 Nginx server
配置的最终结果:
location / {
try_files $uri $uri/ @rewrites;
}
# Rewrite rules to sanitize and canonicalize URLs
location @rewrites {
rewrite ^([^\.]*$(?<!\/)) $1/ last;
}
关于regex - Nginx 重写 : add trailing slash, 保留 anchor 和查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46420985/