【问题标题】:nginx returning 404 after rewriting to url that existsnginx在重写到存在的url后返回404
【发布时间】:2013-06-13 10:09:17
【问题描述】:

我一直在努力解决这个问题,但有人可以帮我弄清楚为什么我的 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 版本中没有前导 lash,因为它不像 nginx 中那样包含在字符串的开头。同样,除了这 2 个之外,所有其他 nginx 规则都可以正常工作。

提前致谢!

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

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

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

【问题讨论】:

  • 我认为您需要从wp\-content 中删除连字符。我刚刚用别名尝试过它,它对我有用:location ~ ^/wp-content/uploads/(.*) { alias /your/absolute/path/here/assets/uploads/$1; }。您最好避免测试文件是否存在以获得更好的性能。或者试试这个:location ~ ^/wp-content/uploads/(.*) { rewrite ^/wp-content/uploads/(.+) /assets/uploads/$1 permanent; }
  • 我不想使用别名,因为我想要一个永久重定向。第二个可能有效,但这并不能让我将图像的标题设置与重写结合起来。正如我在下面的答案中发布的那样,我不得不复制规则(或者我想只是移动它们)。所以不会让我接受我的回答 2 天。
  • 您可以在location 块中直接使用add_header
  • 基本上问题是我无法指定location 块仅适用于存在的文件。

标签: regex url-rewriting nginx rewrite


【解决方案1】:

此块正在匹配和干扰:

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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    • 2013-11-30
    • 2023-02-05
    相关资源
    最近更新 更多