【问题标题】:Nginx: Rewrite Rules Not Working For ImagesNginx:重写规则不适用于图像
【发布时间】:2017-08-28 15:21:59
【问题描述】:

我收到大量以下错误,所有错误都指向在给出错误的位置实际上并不存在的图像,它们是从 Apache 转换的 Nginx 中的重写。

在 Apache 中一切正常,只是因为我切换到 Nginx,图像没有显示,所有其他只是 url 的重写规则都可以正常工作,只有图像坏了?!

错误

2017/04/02 23:15:16 [error] 27629#0: *6 open() "/var/www/html/media/images/blog/10_1.png" failed (2: No such file or directory), client: xxx.xxx.xxx.xxx, server: www.website.com, request: "GET /media/images/blog/10_1.png HTTP/1.1", host: "www.website.com", referrer: "https://www.website.com/blog/"

Apache 重写规则:

## Images
RewriteRule ^media/images/([^/]+)/([^/]+)_([^-]+)_([^-]+)\.png$ /img.php?prefix=$1&refId=$2&thumb=$3&iid=$4 [L]
RewriteRule ^media/images/([^/]+)/([^/]+)_([^-]+)\.png$ /img.php?prefix=$1&refId=$2&thumb=$3 [L]

## Blog Pages
RewriteRule ^blog/$ /?action=blog [L]
RewriteRule ^blog/([a-zA-Z0-9-]+)/$ /?action=blog&category=$1 [L]
RewriteRule ^blog/([a-zA-Z0-9-]+)/([0-9]+)-([a-zA-Z0-9-]+)/$ /?action=blog&category=$1&id=$2&title=$3 [L]

Nginx 重写规则

location /media { 
    rewrite ^/media/images/([^/]+)/([^/]+)_([^-]+)_([^-]+)\.png$ /img.php?prefix=$1&refId=$2&thumb=$3&iid=$4 last; 
    rewrite ^/media/images/([^/]+)/([^/]+)_([^-]+)\.png$ /img.php?prefix=$1&refId=$2&thumb=$3 last; 
}
location /blog { 
    rewrite ^/blog/$ /?action=blog last;
    rewrite ^/blog/([a-zA-Z0-9-]+)/$ /?action=blog&category=$1 last; 
    rewrite ^/blog/([a-zA-Z0-9-]+)/([0-9]+)-([a-zA-Z0-9-]+)/$ /?action=blog&category=$1&id=$2&title=$3 last; 
}

修复

location ^~ /media/images { 
    rewrite ^/media/images/([^/]+)/([^/]+)_([^-]+)_([^-]+)\.png$ /img.php?prefix=$1&refId=$2&thumb=$3&iid=$4 last; 
    rewrite ^/media/images/([^/]+)/([^/]+)_([^-]+)\.png$ /img.php?prefix=$1&refId=$2&thumb=$3 last; 
}
location /blog/ { 
    rewrite ^/blog/$ /?action=blog last;
    rewrite ^/blog/([a-zA-Z0-9-]+)/$ /?action=blog&category=$1 last; 
    rewrite ^/blog/([a-zA-Z0-9-]+)/([0-9]+)-([a-zA-Z0-9-]+)/$ /?action=blog&category=$1&id=$2&title=$3 last; 
}

【问题讨论】:

  • / 添加到位置前缀location /media/ 和文件名的精确正则表达式,例如^/media/images/([^/]+)/(\d+)_(\d+)\.png$

标签: nginx url-rewriting nginx-location


【解决方案1】:

您的配置文件中可能有一个冲突的 location 块,它匹配任何以 .png 结尾的 URI。

您可以通过添加^~ 修饰符使location /media 块的优先级高于正则表达式位置块。

例如:

location ^~ /media { 
    rewrite ^/media/images/([^/]+)/([^/]+)_([^-]+)_([^-]+)\.png$ /img.php?prefix=$1&refId=$2&thumb=$3&iid=$4 last; 
    rewrite ^/media/images/([^/]+)/([^/]+)_([^-]+)\.png$ /img.php?prefix=$1&refId=$2&thumb=$3 last; 
}
location ^~ /blog { 
    rewrite ^/blog/$ /?action=blog last;
    rewrite ^/blog/([a-zA-Z0-9-]+)/$ /?action=blog&category=$1 last; 
    rewrite ^/blog/([a-zA-Z0-9-]+)/([0-9]+)-([a-zA-Z0-9-]+)/$ /?action=blog&category=$1&id=$2&title=$3 last; 
}

请参阅this document 了解更多信息。

【讨论】:

  • 谢谢,您为我指明了正确的方向,我已经用对我有用的修复程序更新了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-07
  • 2018-09-10
  • 1970-01-01
  • 2013-03-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多