apache 使用.htaccess将一个文件夹重定向到另一个文件夹,但保留原始URL并阻止访问所有其他文件夹

6g8kf2rb  于 2023-10-23  发布在  Apache
关注(0)|答案(1)|浏览(151)

tl;dr 如何使用Apache中的 .htaccess 文件将http://test.lab.example.com/mech-platform/(不存在的文件夹)重定向到http://test.lab.example.com/mech-platform-web/frontend/web/(现有文件夹),使用户仍然在浏览器中看到原始URL,无法访问此服务器上的其他任何内容,并且这种重定向不是永久的(未被浏览器缓存)?

问题
我有一个 * test.lab.example.com * 域,它指向一个IP地址,该地址指向Apache安装中的htdocs文件夹。在那里,我有一个现有的mech-platform-web/frontend/web文件夹,这是我的应用程序的Web访问入口文件夹。
我想在该域中使用“假”(不存在)文件夹或URL部分:

  1. http://test.lab.example.com/mech-platform/

指向上述文件夹:

  1. http://test.lab.example.com/mech-platform-web/frontend/web/

web文件夹中的所有文件、URL的所有子部分和所有查询项都必须重写和处理。在此Web可访问文件夹之上的任何其他文件夹或文件都不能访问。
重定向或重写应该对最终用户不可见。例如,所有对“假”URL /文件夹的调用:

  1. http://test.lab.example.com/mech-platform/device/edit/1
  2. http://test.lab.example.com/mech-platform/index.php?device=1&op=edit

必须在现有的基础上进行处理:

  1. http://test.lab.example.com/mech-platform-web/frontend/web/device/edit/1
  2. http://test.lab.example.com/mech-platform-web/frontend/web/index.php?device=1&op=edit

重定向或重写必须是非永久性的。这意味着阅读它的浏览器不能缓存它。如果我删除 .htaccess 文件从我的网络根(http://test.lab.example.com/)的重定向或重写必须停止。任何访问http://test.lab.example.com/mech-platform/的浏览器都必须使用404(在删除 .htaccess 文件夹后),因为这个文件夹实际上并不存在。

解决方案尝试

我是一个Apache配置或修改重写的新手,所以到目前为止,我所能做到的就是复制粘贴SO中找到的修改后的解决方案,调整它们,发现它们不起作用。
例如,我试过这个:

  1. Options +FollowSymLinks
  2. RewriteEngine on
  3. RewriteRule ^(.*)/mech-platform/(.*)$ $1/mech-platform-web/frontend/web/$2 [R,L]

这完全失败了(“请求的URL没有在这个服务器上找到”)。
我也尝试了以下一个:

  1. RewriteEngine on
  2. RewriteCond %{HTTP_HOST} ^test.\lab\.example\.com$
  3. RewriteRule (.*) http://test.lab.example.com/mech-platform/$1 [R=301,L]
  4. RewriteRule ^$ mech-platform-web/frontend/web [L]

这一个失败与“内部服务器错误”。
完全意外的是,我尝试了上面的“测试”子域/部分删除。

  1. RewriteEngine on
  2. RewriteCond %{HTTP_HOST} ^lab\.example\.com$
  3. RewriteRule (.*) http://lab.example.com/mech-platform/$1 [R=301,L]
  4. RewriteRule ^$ mech-platform-web/frontend/web [L]

对于http://lab.example.com/mech-platform/的预期URL,它再次抛出“内部服务器错误”。而当试图访问整个子域-http://lab.example.com/-我得到重定向到正确的子文件夹mech-platform-web/frontend/web
这一定是某种错误/误解的产物。此外,它会产生永久重定向(即使 .htaccess 文件从服务器中删除,浏览器也会缓存并重用它)。使其不可见。用户可以一直看到mech-platform-web/frontend/web文件夹,甚至访问上面的文件夹(如mech-platform-web/frontendmech-platform-web)。在安全方面完全失败。

vddsk6oq

vddsk6oq1#

以下规则应该适用于你在网站根.htaccess:

  1. RewriteEngine On
  2. RewriteCond %{HTTP_HOST} ^test\.lab\.example\.com$ [NC]
  3. RewriteRule ^mech-platform/(.*) mech-platform-web/frontend/web/$1 [NC,L]

如果你想阻止所有其他文件和文件夹的访问者,然后添加此规则结束:

  1. RewriteRule !^(mech-platform-web/|$) [NC,F]

此规则将进行静默重写,并在您删除此.htaccess或注解掉此规则后立即停止工作。

相关问题