使用.htaccess将子目录设置为根目录

时间:2012-02-23 12:31:46

标签: php .htaccess directory rewrite root

有没有办法使用htaccess告诉子目录充当整个网站的根目录?

例如,如果我在http://localhost/testsite/下有一个网站,并且在index.php文件中,我使用以下代码引用了样式表。

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

我可以加载/localhost/testsite/css/layout.css吗?

为了解决这个问题,我为每个网站设置了localhost子域,虽然有效,但并不理想。

非常感谢。

2 个答案:

答案 0 :(得分:20)

如果你想保留'href =“/ css / layout.css”'部分,那么是的,你可以设置一个重写规则。你必须小心不要重定向以/ testsite开头的任何东西(或者你最终会得到一个循环)。

喜欢(在根.htaccess中):

RewriteEngine On

RewriteCond %{REQUEST_URI} !^/testsite/.*$
RewriteRule ^(.*)$ /testsite/$1 [QSA,L]

在那里,您可以从以下位置访问layout.css文件:

http://localhost/testsite/css/layout.css

http://localhost/css/layout.css

答案 1 :(得分:3)

当然,所有相对URI(与您的相对)都是相对于基本URI的,默认情况下是基本URI:

http://localhost/testsite/index.php

您只需要告诉要添加哪个部分:

<link rel="stylesheet" type="text/css" href="./css/layout.css" />
                                             ^
                                             ` see this dot

示例:

Base URI      ::  http://localhost/testsite/index.php
Relative URI  ::  ./css/layout.css
Result        ::  http://localhost/testsite/css/layout.css

如果您需要更加模块化,有多种方法可以做到这一点。一种是在HTML文档中明确设置基本URI(参见<base>)。

另一种方法是根据 Request URI 和您网站的根路径,在服务器端相对解析链接。有关示例,请参阅this answer