php 使用 .htaccess 将子目录设置为根目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9413127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using .htaccess to set a sub directory as root directory
提问by Stibily
Is there a way to use htaccess to tell a subdirectory to act as the root for the entire site?
有没有办法使用 htaccess 告诉子目录充当整个站点的根目录?
For example, if I had a website under http://localhost/testsite/and in it's index.php file I had a reference to the stylesheet using the following code..
例如,如果我在http://localhost/testsite/下有一个网站,并且在它的 index.php 文件中,我使用以下代码引用了样式表。
<link rel="stylesheet" type="text/css" href="/css/layout.css" />
Could I then make that load /localhost/testsite/css/layout.css?
然后我可以加载 /localhost/testsite/css/layout.css 吗?
To get around this problem, I set up localhost subdomains for each site which although works, is not ideal.
为了解决这个问题,我为每个站点设置了 localhost 子域,这虽然有效,但并不理想。
Many thanks.
非常感谢。
回答by huelbois
If you want to keep the 'href="/css/layout.css"' part, then yes, you can set up a rewrite rule. You just have to be careful not to redirect anything starting with /testsite (or you'll end up with a loop).
如果您想保留 'href="/css/layout.css"' 部分,那么是的,您可以设置重写规则。您只需要注意不要重定向以 /testsite 开头的任何内容(否则最终会出现循环)。
Like (in root .htaccess):
喜欢(在根 .htaccess 中):
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/testsite/.*$
RewriteRule ^(.*)$ /testsite/ [QSA,L]
There, you will be able to access your layout.css file either from:
在那里,您将能够从以下任一方式访问您的 layout.css 文件:
http://localhost/testsite/css/layout.css
http://localhost/testsite/css/layout.css
or
或者
回答by hakre
Sure, all relative URIs (as yours) are relative to the base URI which by default is the URI of the document:
当然,所有相对 URI(如您的)都是相对于基本 URI 的,默认情况下它是文档的 URI:
http://localhost/testsite/index.php
You only need to tell which part to add:
您只需要告诉添加哪个部分:
<link rel="stylesheet" type="text/css" href="./css/layout.css" />
^
` see this dot
Example:
例子:
Base URI :: http://localhost/testsite/index.php
Relative URI :: ./css/layout.css
Result :: http://localhost/testsite/css/layout.css
If you need to have this more modular, there are multiple ways to do that. One is to set the base URI explicitly inside the HTML document (see <base>
).
如果您需要更模块化,有多种方法可以做到这一点。一种是在 HTML 文档中显式设置基本 URI(请参阅 参考资料<base>
)。
Another one is to resolve links relatively on the server-side based on the Request URIand your site's root-path. See this answerfor an example.
另一种方法是根据请求 URI和站点的根路径在服务器端相对解析链接。有关示例,请参阅此答案。