nginx在重写为存在的url后返回404

时间:2013-06-12 23:47:22

标签: regex url-rewriting nginx rewrite

我一直在敲打这个问题一段时间,但有人可以帮助我弄清楚为什么location /区块中的这个与http://chrisbenard.net/wp-content/uploads/2010/12/chromeosalbum.png不匹配?

匹配并将http://chrisbenard.net/wp-content/uploads/2010/12/重定向到http://chrisbenard.net/assets/uploads/2010/12/

文件chromeosalbum.png显然位于正确的目录中。此问题扩展到该目录下的所有文件。

if (!-e $request_filename){
  rewrite ^/wp\-content/uploads/(.+)? /assets/uploads/$1 permanent;
}

此外,我希望/?s=query转到/search/#?query=query。我试过了:

rewrite ^/\?s\=(.*)$ /search/#?query=$1;

那个人也没有做到这一点。我的所有其他正则表达式替换工作正常。我已经从wordpress安装迁移到PieCrust,这就是我需要做所有这些重定向的原因。

我使用(.*)(.*)?(.+)以及其他一些变体尝试了第一个正则表达式。我甚至尝试用wp\-content替换.*content,以为可能以某种方式搞砸了逃脱。我没有运气。

编辑:此外,这个相同的正则表达式在Apache中运行良好(对于资产目录;我无法使搜索正则表达式工作)。我正在使用它:

RewriteBase /
...
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^wp\-content/uploads/(.*)? /assets/uploads/$1 [NC,R=301,L]

apache版本中没有前导冲突,因为它不包含在字符串的开头,就像它在nginx中一样。同样,除了这两个规则之外,所有其他nginx规则都正常工作。

提前致谢!

编辑2:事实证明,只有在重写目的地存在时才会发生。

例如,这会重定向到正确的网址: http://chrisbenard.net/wp-content/uploads/2010/12/garbage.file.png

这不会重定向到正确的网址,只返回404(但如果您将wp-content更改为资源,则会加载正常): http://chrisbenard.net/wp-content/uploads/2010/12/chromeosalbum.png

1 个答案:

答案 0 :(得分:0)

这个区块是匹配和干扰的:

location ~* \.(?:ico|svg|css|js|gif|jpe?g|png)$ {
    expires 3d;
    add_header Pragma public;
    add_header Cache-Control "public";
}

即使我这样做,我仍然有一个问题:

location ~* \.(?:ico|svg|css|js|gif|jpe?g|png)$ {
    if (-e $request_filename) {
        expires 3d;
        add_header Pragma public;
        add_header Cache-Control "public";
    }
}

我最终只是在匹配的位置复制了一些重写规则并且它有效,但我不明白为什么。我想这只是最具体的匹配,所以它忽略了location /中的规则。

location ~* \.(?:ico|svg|css|js|gif|jpe?g|png)$ {
    if (-e $request_filename) {
        expires 3d;
        add_header Pragma public;
        add_header Cache-Control "public";
    }

    if (!-e $request_filename){
        rewrite "^/wp\-content/uploads/(.+)?" /assets/uploads/$1 permanent;
    }
    if (!-e $request_filename){
        rewrite ^/images/(.*)? /assets/images/$1 permanent;
    }
}