regex - 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。
解决方案
这应该有效:
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
,然后捕获任何东西(如果有的话)
推荐阅读
- wget - 使用 Wget 下载包含所有支持 css/js/img 文件的网页
- elasticsearch - 使用 Elasticsearch 在 AWS ECS 上部署 jaeger
- node.js - 为什么 Chrome 从 2 个端口连接到我的 nodejs 服务器?
- webpack - 如何将 sourcemap 添加到我自己的 webpack 加载器?
- angular - 角度响应数据未显示在 html 页面中
- angular - Observable 最终无法从 err 状态传入
- python - Flask:如何使用 SQLAlchemy 从 PostgreSQL 获取多个值?
- reactjs - 如何制作一个反应式直播应用程序?
- nuget - 缺少旧包时如何更新 Nuget 包?
- javascript - 如何根据 Vanilla Javascript 中的菜单控制列?