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


Using .htaccess to set a sub directory as root directory

有没有一种方法可以使用htaccess告诉子目录充当整个站点的根目录?

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

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

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

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

非常感谢。

如果您想保留'href="/css/layout.css"'部分,那么是的,您可以设置重写规则。您只需要小心,不要重定向以/testsite开头的任何内容(否则将导致循环)。

类似(在root.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

当然,所有相对URI(如您的)都是相对于基本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>)。

另一种方法是基于请求URI和站点的根路径在服务器端相对解析链接。请参阅此答案以获取示例。