为什么我的php文件在使用RewriteRule时无法定位外部文件(image,css..)


Why is my php file unable to locate external files (image,css...) when using RewriteRule?

我正在使用以下重写规则:

RewriteRule ^([a-zA-Z0-9]+)$ page.php?p=$1
RewriteRule ^e/([a-zA-Z0-9]+)$ edit.php?p=$1

第一个很好:当输入mysite.com/id时,它会加载mysite.com/page.php?p=服务器端的id。

第二个也在工作:当我键入mysite.com/e/id时,它会加载mysite.com/edit.php?p=id(如预期)。但在这种情况下,edit.php无法加载任何外部文件,比如我的css文件。

<link rel="stylesheet" type="text/css" href="style.css" />

执行任一操作时:

<link rel="stylesheet" type="text/css" href="../style.css" />

或者简单地删除重写规则中的目录,如:

RewriteRule ^e_([a-zA-Z0-9]+)$ edit.php?p=$1

它解决了这个问题。

现在我不明白为什么我的edit.php无法定位外部文件,即使它加载在服务器端(mysite.com/)的正确路径上,也不喜欢url显示在额外的目录中(在本例中为mysite.com/e/)。

您可以为所有网站的路径使用一个基本url,如下所示:

<base href="http://yoursite.com/blog/" />

<base href="/blog/" />

然后从基础的写入相对路径

<a href="rule/foo/">...</a>

此外,你必须格外小心那些"全盘接受"的模式,因为如果使用不当,它们可能会与样式表、图像和其他媒体发生冲突。可能的修复方法是在模式中添加扩展名或排除介质。

使用mod_rewite 时,必须写入完整路径,而不是相对路径

参考

apache mod重写
再来一次
初学者指南