【问题标题】:Redirect to subdirectory path for the page links having absolute path重定向到具有绝对路径的页面链接的子目录路径
【发布时间】:2021-04-02 21:38:51
【问题描述】:

例如,主 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/

预期行为:

  1. 我想从 root/projects/thekingfisher/ 加载文件“css/styles.css”
  2. 此外,“关于”链接应导航至“http://example.com/projects/thekingfisher/about.php”

实际情况:

  1. 正在搜索要加载的 root/css/ 中的 style.css 文件。
  2. “关于”链接导航到“http://example.com/about.php”

实际上,项目在 root 上运行顺利。但没有正确加载到子目录中。 这种模式有很多超链接,尝试时会出现404错误。 由于这是一个活动项目,我不想在源文件中进行编辑以修改路径,例如添加 baseurl 等。

【问题讨论】:

  • 您是否尝试将完整链接放入href 部分?或者将其更改为"./" + rest_of_link
  • 是的,然后就可以了。即使我删除了第一个斜线,它也可以工作。我不想对项目中的每个文件进行更改。相反,我想要使用 httaccess 的解决方案或其他需要很少编辑影响整个项目的解决方案。
  • “./”应该告诉它你想从当前目录开始搜索文件,而不是从根目录开始

标签: php apache .htaccess


【解决方案1】:

您只需要站点根目录中的一条规则即可将所有请求重写为/projects/thekingfisher/

RewriteEngine On

# if file exists in /projects/thekingfisher/ then rewrite
RewriteCond %{DOCUMENT_ROOT}/projects/thekingfisher/$0 -f
RewriteBase .* projects/thekingfisher/$0 [L]

【讨论】:

  • 根目录下还有很多其他的东西在运行。因此,在不打扰他们的情况下,我最好希望在 /projects/thekingfisher/ 中使用 .htaccess 解决方案
  • /projects/thekingfisher/.htaccess 无法控制 example.com/about.php 的 URI,但我将修改站点根 .htaccess 以仅针对 /projects/thekingfisher/ 中的现有文件处理它
  • 这个有道理,我一定会先查的。
  • 没有按预期工作,我收到 500 内部服务器错误
  • 这并不能说明什么。你还在为 http://example.com/about.php 获得 404 吗?您可以仅检查此规则以进行测试吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-25
  • 2021-04-05
  • 2014-11-26
  • 2020-08-07
  • 2016-10-07
  • 2020-09-26
相关资源
最近更新 更多