【问题标题】:Nginx multiple conditions for rewriteNginx 重写的多重条件
【发布时间】:2014-05-22 10:16:42
【问题描述】:

我的nginx配置如下

  location /eicnews/ {
  set $con "";

  if ($request_uri ~ ^/eicnews\/(.*)$) {
    set $con  A;
  }

  if ($request_uri ~ ^/eicnews\/$) {
    set $con  "${con}B";
  }

  if ($con = A) {
rewrite ^/eicnews\/eicnewscontent_(.*)\.shtml$ http://news.abc.cn/eic/news_$1.shtml permanent;
        }

        if ($con = AB) {
rewrite ^/eicnews\/(.*)$ http://news.abc.cn/eic permanent;

        }

}

我的配置意味着 1.如果客户端请求名为“/eicnews/”的directoty将被重写为url/dir 2.如果客户端请求包含名为“/eicnews/”的目录的文件将被重写为url/dir/files

但是现在“/eicnews/”中有两种文件名,eicnewscontent_xxxx.shtml和eicnewslist_xxxx.shtml,我想如果前缀“eicnewscontent”文件被重写为http://news.abc.cn/eic/news_$1.shtml和前缀“eicnewslist”会改写为http://news.abc.cn/eic

谢谢大家!!!!

我的意思是,目录中有2种前缀文件,例如eicnewslist_xxxxx.shtml和eicnewscontent_xxxxx.shtml,前缀“eicnewslist”重写为一个url,前缀“eicnewscontent”重写到另一个url。我想要它如下.语法没问题。但它不起作用。

location =  /eicnews/ {

        rewrite  ^/eicnews/eicnewslist(_.*\.shtml)$  http://news.smartjs.cn/eic$1 permanent;
    }
    location /eicnews/ {
        rewrite ^/eicnews/eicnewscontent(_.*\.shtml)$ http://news.smartjs.cn/eic/news_xx.shtml$1 permanent;
    }

【问题讨论】:

  • location /eicnews/ 内部,您的第一个if 始终为真(除非您有其他一些未显示的重写)。在这种情况下,你的三分之二 if 总是错误的。那么,您能否解释一下您要重写哪些 URL 以及改写什么。有一些样品。
  • 谢谢,我打错字了。在第三个 if 子句中“set $con =A not B”。我已经更正了:)。

标签: nginx url-rewriting


【解决方案1】:

尽量避免ifs。阅读http://wiki.nginx.org/IfIsEvil

在你的情况下,我会做以下事情:

location = /eicnews/ {
    rewrite ^ http://news.abc.cn/eic permanent;
}

location /eicnews/ {
    rewrite ^/eicnews/eicnewscontent(_.*\.shtml)$ http://news.abc.cn/eic/news$1 permanent;
}

我不确定你想对/eicnews/other-path 的请求做什么。

【讨论】:

  • 您希望将所有eicnewslist_ANYTHING 重定向到一个网址http://news.abc.cn/eic
  • @XuYuanzhen,我再次询问示例。请提出问题,在cmets中无法读取它们。
  • 我已经修复并期待您的出色回答。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-15
  • 2016-03-27
  • 2018-01-13
  • 1970-01-01
  • 1970-01-01
  • 2016-02-12
  • 2014-11-10
相关资源
最近更新 更多