我试图重定向,如果一个图像不存在于我的网站


I am trying to redirect if an image does not exist on my site

我有一个网站,如果用户去www.example.com/string,如果string.jpg存在于www.example.com/images/profile/中,那么我希望它重定向到www.example.com/index.php?u=string,但如果图像不存在,我希望它重定向到www.example.com

我尝试在。htaccess

中使用以下内容
RewriteRule ^(.*)$ /index.php?u=$1 [NC,L,QSA]

但是这会重定向所有内容即使图像不存在

所以,如果用户请求页面A,文件B存在,转到C?

我不认为apache开发人员认为只有当某些重定向存在时才有用。至少我看不出目的。

但是如果所有内容都重定向到index.php,那么将检查文件是否存在的代码放在那里,如果不存在,则让index.php再次重定向到首页。

但是,index.php不是默认页面吗?

您需要检查是否file_exists('filename'),一个已经存在的PHP函数

然后你可以使用相应的PHP头重定向。

这将完全避免RewriteRule,你可以添加适当的PHP头。

为了使此工作,您需要在URL中检测文件.jpg,将请求发送到PHP文件(检查文件是否存在),然后最后使用PHP重定向头进行重定向。

您需要使用RewriteCond检查文件是否存在。如果是,则重定向到该图像,否则将请求传递给index.php

# Make sure it's not a direct URL to a file or a directory.
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
# Check if the request URI exists in the images folder.
RewriteCond %{DOCUMENT_ROOT}/images/profile%{REQUEST_URI}.jpg -f
# If the image exists, redirect to that.
RewriteRule ^ %{DOCUMENT_ROOT}/images/profile{%REQUEST_URI}.jpg [L]
# By default, pass the request string to our application.
RewriteRule ^ index.php?u=%{REQUEST_URI} [L,QSA]

为什么不在php中这样做呢?您的重写规则重定向了所有内容,因此保留它。现在在index.php中添加以下代码:

<?php
if( isset($_GET['u']) && !file_exists('./images/profile/'.basename($_GET['u'])) ) {
    header('Location: http://www.example.com');
    exit(0);
}
//Do all your other wonderful stuff here.. for instance:
if( isset($_GET['u']) && file_exists('./images/profile/'.basename($_GET['u'])) {
    header('Content-Type: image/png');
    readfile('./images/profile/'.basename($_GET['u']));
    exit(0);
} else {
    echo("Hello world!");
}

显然要小心不要创建无限循环重定向(例如,如果index.php是您的默认页面,重定向到默认页面将使人们陷入被重定向到同一页面的无限循环)。