简体   繁体   English

Nginx位置重定向正则表达式不起作用

[英]Nginx location redirect regex not working

I want to redirect requests to /images/someimage.png on my server to http://some.other.server/images/someimage.png . 我想将请求重定向到服务器上的/images/someimage.png到http://some.other.server/images/someimage.png I have the following in my nginx config: 我的nginx配置中包含以下内容:

location ^/images/.*(png|jpg|gif)$ {
    rewrite ^/images/(.*)(png|jpg|gif)$ http://anotherserver.com/images/$1$2 redirect;
    return   302;
}

But for some reason it isn't getting hit when I request http://test.com/images/test.png (I just get a 404 because that file doesn't exist on myserver). 但是由于某种原因,当我请求http://test.com/images/test.png时,它没有被击中(我只得到一个404,因为该文件在我的服务器上不存在)。

If i understand you correctly you want to 302 redirect /image/ url's on one server to the same path on another server. 如果我正确理解您的要求,则要302将一台服务器上的/ image / url重定向到另一台服务器上的相同路径。 You can do that like so: 您可以这样做:

location /images/ {
  rewrite ^ $scheme://anotherserver.com$request_uri redirect;
}

you don't need the return 302 the rewrite ... redirect already does that (if you want 301 redirects instead use rewrite .... permanent ) 您不需要return 302 rewrite ... redirect已经做到了(如果您想301重定向,请使用rewrite .... permanent

you don't need regexes as long as you have the same url's on the other server either, the builtin variables will suffice 只要您在另一台服务器上具有相同的url,就不需要正则表达式,内置变量就足够了

NOTE: The reason your location isn't getting hit is that you have location ^/images/.*(png|jpg|gif)$ instead of location ~ ^/images/.*(png|jpg|gif)$ . 注意:您的位置未被点击的原因是您具有location ^/images/.*(png|jpg|gif)$而不是location ~ ^/images/.*(png|jpg|gif)$ In other words you forgot to signal regex matching (with ~ for case-sensitive or ~* for case-insensitive) 换句话说你忘记信号正则表达式匹配(具有~对于区分大小写或~*为不区分大小写)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM