【问题标题】:Apache show a default image when there is a 404 error under a specific URL pattern当特定 URL 模式下出现 404 错误时,Apache 会显示默认图像
【发布时间】:2016-07-30 19:04:59
【问题描述】:

在纯基于客户端的网络应用程序中,我需要显示有时不存在的背景图像。当特定的 URL 模式返回 404 错误时,有没有办法“强制”Apache 提供图像?

可能返回 404 的 URL 模式是:

http://host/assets/user-images/xxxxx.jpg

我想在哪里提供图片:

http://host/assets/user-images/default.jpg

注意:

我已经使用了 .htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

【问题讨论】:

    标签: apache .htaccess http-status-code-404 url-pattern


    【解决方案1】:

    在文件“/assets/user-images/.htaccess”中添加以下内容

    RewriteCond %{REQUEST_URI} ^/assets/user-images/(.*)\.jpg$ 
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ default.jpg
    

    第一个 RewriteCond 将检查传入的请求是否为 /assets/user-images/ 下的 jpg 文件,第二个带有 -f 选项的 RewriteCond 将检查请求的文件是否存在。如果它不存在,则 RewriteRule 将提供默认图像。 最终用户仍将看到原始图像的 URL,但将提供默认图像。 如果原始图像文件存在,则不会执行此规则。

    【讨论】:

    • 是的,它按预期工作。尽管我最终使用了 Slim 的“notFoundHandler”,但它是您提供的一个非常强大的解决方案。
    猜你喜欢
    • 2017-05-05
    • 1970-01-01
    • 2011-11-21
    • 2013-02-02
    • 1970-01-01
    • 2020-01-04
    • 2017-07-07
    • 2012-11-17
    • 2016-11-30
    相关资源
    最近更新 更多