php - 重定向到具有绝对路径的页面链接的子目录路径
问题描述
例如,主 URL 是在 apache 服务器上运行的http://example.com 。
我想将我的项目作为 root>projects>thekingfisher 放在子目录中,从而导致
http://example.com/projects/thekingfisher/
使用 htaccess,我可以访问该项目
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /projects/thekingfisher/
</Ifmodule>
但是,某些文件具有绝对路径,如下文件所示无法访问
/root/projects/thekingfisher/index.php
<html>
<head>
<link href="/css/styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Test Page</h1>
<a href="/about.php">About</a>
</body>
</html>
当我运行我的项目http://example.com/projects/thekingfisher/
预期行为:
- 我想从 root/projects/thekingfisher/ 加载文件“css/styles.css”
- 此外,“关于”链接应导航到“http://example.com/projects/thekingfisher/about.php”
实际场景:
- style.css 文件正在 root/css/ 中搜索以加载。
- “关于”链接导航到“http://example.com/about.php”
实际上,项目在 root 上运行顺利。但没有正确加载到子目录中。这种模式有很多超链接,尝试时会出现404错误。由于这是活动项目,我不想在源文件中进行编辑以修改路径,例如添加 baseurl 等。
解决方案
您只需要站点根目录中的规则即可将所有请求重写为/projects/thekingfisher/
:
RewriteEngine On
# if file exists in /projects/thekingfisher/ then rewrite
RewriteCond %{DOCUMENT_ROOT}/projects/thekingfisher/$0 -f
RewriteBase .* projects/thekingfisher/$0 [L]