首页 > 解决方案 > nginx 重写删除 html 除非 URL 包含字符串

问题描述

我们需要将所有包含html的链接重定向到非html,例如:

domain.com/post.html -> domain.com/post domain.com/2010/10/post.html -> domain.com/2010/10/post

但是我们需要排除路径中包含“插件”的 URL,例如:

domain.com/wp-content/plugins/something/test.html 不应重定向。

尝试通过以下方式完成此操作:

rewrite ^(/.*)\.html(\?.*)?$ $1$2 permanent;

并在后面添加一个否定的lookbehind:

rewrite ^(?!plugins)(/.*)\.html(\?.*)?$ $1$2 permanent;

我尝试的任何变化似乎都有问题。或者即使 URL 中包含插件,仍会从 URL 中删除 .html。

标签: regexnginxurl-rewriting

解决方案


这应该有效:

rewrite ^(?!/[^/]+/plugins/)(/.*)\.html(\?.*)?$ $1$2 permanent;

测试:

/post.html         ==> domain.com/post
/post.html?foo=bar ==> domain.com/post?foo=bar
/2010/10/post.html ==> domain.com/2010/10/post
/wp-content/plugins/something/test.html (no match)

正则表达式的解释:

  • ^... $- 在开始和结束处锚定
  • (?!/[^/]+/plugins/)/plugins/-在第二个子目录中预期负前瞻
  • (/.*)\.html(\?.*)?$- 捕获之前的任何东西.html,然后捕获任何东西(如果有的话)

推荐阅读