使用.htaccess重定向而不更改URL

时间:2014-04-11 14:33:52

标签: php .htaccess web-applications web

我想从图片网址重定向到网址。

即。 nevil120.herobo.com/images/Chrysanthemum.jpg      至      nevil120.herobo.com/index.php?image=free

应该进行重定向,但不应在浏览器中更改url。网址应保留为nevil120.herobo.com/images/Chrysanthemum.jpg,页面应加载。

如何通过.htaccess的重定向规则实现它?

1 个答案:

答案 0 :(得分:0)

你可以这样做:

Options +FollowSymLinks
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} \.(jpg)$ [NC]    
RewriteRule RewriteRule ^images/([^/]+)$ index.php?image=free [QSA,L]

这会将带有.jpg扩展名的所有图片重定向到index.php?image=free。 如果您希望images/Chrysanthemum.jpg重定向到index.php?image=Chrysanthemum.jpg,您可以执行以下操作:

RewriteRule ^images/([^/]+)$ index.php?image=$1 [QSA,L]

注意:QSA标志会将原始网址中的所有参数附加到新网址。这意味着如果有人前往images/Chrysanthemum.jpg?image=dandelion$_GET['image']变量将是蒲公英。要仍然获得第一个图像参数(Chrysanthemum.jpg),您可以在php中使用以下正则表达式:

$image = preg_replace('/image=([^&]+).*/', '$1', $_SERVER['QUERY_STRING']);

或者你可以删除QSA标志