Nginx:重写规则不适用于图像

时间:2017-04-03 16:46:03

标签: nginx url-rewriting nginx-location

我收到了大量以下错误,所有错误都指向实际存在于发生错误的位置的图像,它们在Nginx中重写,这些错误是从Apache转换的

一切都在Apache工作正常,只是因为我切换到Nginx,图像没有显示,所有其他重写规则只是网址都工作正常,只有图像破碎? !

错误

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

1 个答案:

答案 0 :(得分:2)

您的配置文件中可能存在冲突的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