nginx 不区分大小写重写

nginx 不区分大小写重写

我正在尝试使我的 nginx 重定向尽可能干净。我理解 ~* 不区分大小写,但我只能在示例 2 中使用它。

示例 1

rewrite ^/foobar http://www.youtube.com/watch?v=oHg5SJYRHA0 redirect;

示例 2 - 这可行,但不如上面那行那么高效。

if ( $request_filename ~* foobar ) {
         rewrite ^ http://www.youtube.com/watch?v=oHg5SJYRHA0 redirect;
   }

有没有办法使用示例 1 进行不区分大小写的重定向,而不会使其变得太混乱?

谢谢。

答案1

我刚刚遇到(并修复了)同样的问题,最后来到这里寻找答案。nginx 文档(http://nginx.org/en/docs/http/ngx_http_rewrite_module.html),并没有明确指出 ~* 仅在 if 语句中起作用,但显然情况确实如此。

为了在 if 语句之外获得 ngnix URL 重写的不区分大小写的正则表达式匹配,我必须使用 Apache/Perl 样式:

rewrite "(?i)foobar" http://www.youtube.com/watch?v=oHg5SJYRHA0 redirect;

http://perldoc.perl.org/perlretut.html(搜索不敏感的)。似乎在特定捕获组之外添加前缀 (?i) 也会使其适用于整个搜索字符串。注意:这似乎不适用于“^(?i)foobar”,因为似乎隐含了“^”。

不过,为了确保万无一失,并且为了使将来的任何重写都更容易维护,并且在您最终进行大量重写时不会产生太多歧义,您可能需要执行以下操作:

location /foobar {
     rewrite "(?i)" http://www.youtube.com/watch?v=oHg5SJYRHA0 redirect;
}

希望这可以帮助...

答案2

我发现可以做到这一点的方法如下:

rewrite ^/foobar http://www.youtube.com/watch?v=oHg5SJYRHA0 redirect;

你只需要这样做:

rewrite (?i)^/foobar http://www.youtube.com/watch?v=oHg5SJYRHA0 redirect;

这仅意味着添加(?i),否则匹配的所有内容都相同。

答案3

我现在正在开发一个网站,我发现这似乎是一种简单的方法。在服务器块中,你只需要按顺序添加位置条目,如下所示:

#This rule processes the lowercase page request.
#The (~) after the location tag specifies it is case sensitive
# so it overrides the next rule, which would continuously redirect
location ~ /index[.]html {
#process the index.html page       
}

#This rules rewrites the index request which may be non-case-sensitive
# to all lowercase so the previous rule can process it.
location ~* /index[.]html {
   rewrite ^(.*)$ $scheme://$http_host/index.html redirect;
}

相关内容