我有一个用于清理URL:的mod_rewrite规则
RewriteRule ^tshirts*$ /thsirt.php
其思想是访问myurl.com/tshirt
或myurl.com/tshirts
应该重定向到myurl.com/tshirt.php
。
访问myurl.com/tshirt
正确地显示了tshirt.php
,直到我向tshirt.php
添加了一个外部样式表链接——现在它实际上重定向到了CSS文件,所以我只剩下CSS文件的原始源(tshirt.css
)。
更令人困惑的是,如果我导航到myurl.com/tshirts
,它会抛出404。
tshirt.php
来源:
<html>
<head>
<title>Page title</title>
<link rel="stylesheet" type="text/css" href="/tshirt.css" />
</head>
<body>
<h1>Hello, world.</h1>
</body>
</html>
tshirt.css
来源:
body{
background-color: #4F5557;
}
知道是什么原因导致的吗?或者如何解决?
最好的解决方案是覆盖所有的基础,基本上确保只重写需要重写的内容,而不重写不应该重写的内容。
首先,默认情况下,您应该注意不要重写任何引用特定文件或目录的内容,使用:
# Do Not apply if a specific file or folder exists
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
添加以下Next还允许您指定要忽略规则的某些目录,这些目录可能用于其他目的,例如调用的脚本或要从外部链接到的资源。
# Do Not apply if refering to a resource in one of these folders
RewriteCond %{REQUEST_URI} "/admin/" [OR]
RewriteCond %{REQUEST_URI} "/scripts/" [OR]
RewriteCond %{REQUEST_URI} "/external/"
RewriteRule (.*) $1 [L]
最后,你可以拥有你的规则
RewriteRule ^tshirts*$ /tshirt.php
通常情况下,您不希望任何现有文件或目录的url被重写,因此在您的规则之前,您添加了两个条件:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^tshirts*$ /thsirt.php
为不同类型的资源提供清晰的文件夹结构也有助于保持项目的可管理性。