如何使用 htaccess 使子文件夹充当文档根目录


How do I make a subfolder act like a document root using htaccess?

站点位置: http://localhost/~username/website

该网站加载了许多带有绝对URL的图像,例如/image/image.png。

我需要该请求转到:http://localhost/~username/website/image/image.png而不是http://localhost/image/image.png。

我还需要它来不影响任何其他文件夹或根文件夹。这样,如果我愿意,我也可以访问 http://localhost/image/image.png。

有没有办法做到这一点,以便在从这个子文件夹请求它重定向时?

我希望像/css/something.css 和/image/image.png 这样的绝对引用指向/subdirectory/css/something.css 和/subdirectory/image/image.png。这样我就不必重写所有绝对引用。所以,我不想修改根目录。

我想知道是否设置一个不允许子目录"网站"无法访问根目录的虚拟主机。我永远不需要此文件夹的root访问权限。

确保允许您在网络服务器中使用.htaccess文件。看看如何在 apache 中启用:https://www.digitalocean.com/community/tutorials/how-to-use-the-htaccess-file

在根目录或 ~用户名/网站目录中创建一个 .htaccess 文件,然后将其写入您的 .htaccess 文件:

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^~username/web/image/(.*) /image/$1

为什么要求使用 /image/image.png ?您为什么不直接使用以下之一:

http://localhost/~username/website/image/image.png (absolute)
image/image.png (relative without preceding slash)

您可以在根 .htaccess 或 Apache/vhost 配置中使用此规则:

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/~
RewriteRule ^(.*)$ ~username/website/$1 [L]