首页 > 解决方案 > Nginx 重写 url 的最后一个片段

问题描述

我想将 url ' https://www.example.com/knowledges/qa/123456 ' 转换为' https://www.example.com/knowledges/qa.html?id=123456 'Nginx

我是 Nginx 的新手并尝试以下操作:

root   /opt/statics;

location / {            
   index index.html;
}

location /knowledges/qa/ {
   rewrite ([^\/]+)\/?$ /knowledges/qa.html?questionId=$1 last;
}

正则表达式/([^\/]+)\/?$/g可以匹配 url 的最后一个片段的组(即 123456)。

== 编辑 ==

添加最后一个斜线/knowledges/qa/作品。(否则死循环)

然后,新的问题出现了。在qa.html检索文档位置:

document.location.href // https://www.example.com/knowledges/qa/123456

不像https://www.example.com/knowledges/qa.html?id=123456预期的那样?

标签: nginxnginx-location

解决方案


我相信不会[^/]+匹配。尝试knowledges123456

rewrite ^/knowledges/qa/(\d+)$ /knowledges/qa.html?questionId=$1 last;

推荐阅读