【问题标题】:How to redirect in nginx if request URI does not contain certain words如果请求 URI 不包含某些单词,如何在 nginx 中重定向
【发布时间】:2018-02-21 02:45:43
【问题描述】:

我正在使用 nginx 来提供静态新闻类页面。 在顶层有 https://example.com/en/news/ 带有文章概述。 单个项目的 URL 类似于:https://example.com/en/news/some-article

所有网址都包含语言,即/en//de/。 我想创建一个规则,将包含语言的请求重定向到正确的 URL(语言基于 IP 映射,可通过$lang 获得)。

以下应该可以工作(en 示例):

/news/             --- redirect ---> /en/news/
/news/some-article --- redirect ---> /en/news/some-article

我的尝试看起来像这样

location ~* /news/.*$ {
    if ($request_uri !~* /(de|en)/$) {
        return 302 https://example.com/$lang/$request_uri;
    }
}

到目前为止,这导致了无限重定向。

【问题讨论】:

标签: regex nginx nginx-location


【解决方案1】:

您的解决方案对我来说似乎过于复杂。并且使用尾随 $ 测试 $request_uri 将永远不会匹配重写的 URI(因此是循环)。

您可以使用前缀 location 来仅匹配以 /news/ 开头的 URI。

假设您在别处计算了 $lang 的值,这可能对您有用:

location ^~ /news/ {
    return 302 /$lang$request_uri;
}

^~ 修饰符仅在您的配置中有正则表达式 location 块可能发生冲突时才是必需的。请参阅this document 了解更多信息。

【讨论】:

  • 谢谢,这有帮助 - 甚至避免了if,我认为这更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-22
  • 2016-03-23
  • 1970-01-01
  • 2017-12-26
  • 2014-12-09
  • 1970-01-01
相关资源
最近更新 更多