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

Nginx: Rewrite Rules Not Working For Images

我收到大量以下错误,所有错误都指向在给出错误的位置实际不存在的图像,它们是在从 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=&refId=&thumb=&iid= [L]
RewriteRule ^media/images/([^/]+)/([^/]+)_([^-]+)\.png$ /img.php?prefix=&refId=&thumb= [L]

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

Nginx 重写规则

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

修复

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

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

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

例如:

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

有关更多信息,请参阅 this document