.htaccess > 将所有子文件夹重定向到根目录(忽略尾部斜杠)

.htaccess > redirect all subfolders to root (ignore trailing slash)

我的天哪 - 我讨厌 .htaccess ...并且不明白到底是怎么回事。 我试图忽略 'subfolders' 并将它们用作来宾标识符。 例如:

User types > http://subdomain.domain.com/guest_id

Server sends > http://subdomain.domain.com/index.php

Browser shows > http://subdomain.domain.com/guest_id

我的 htaccess 文件:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) index.php [NC]

代码运行良好...除非有尾部斜杠。 在这种情况下,所有文件都作为 'index.php'。 主要 Index.php 显示正确,但所有外部脚本 / css / 等都作为 /guest_id/index.php (因此......不要加载)。

仅供参考,可能存在冲突,因为我的 'subdomain' 实际上是在不可见的服务域。com/event/

我已经尝试了很多排列组合...但并没有真正理解 htaccess 的工作原理。

非常感谢您的帮助。 1,000 提前致谢! 达米恩

当您有 URL 例如 http://subdomain.domain.com/guest_id/ 并且正在为您的 css/js/images 使用 相对链接 时,浏览器会尝试解析所有链接在它们前面加上当前路径因此 src='image.png' 被解析为 http://subdomain.domain.com/guest_id/image.png 而不是 http://subdomain.domain.com/image.png.

您可以有一个规则强制删除所有非目录 URL 末尾的斜线。

RewriteEngine On

# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^(.+)/+$
RewriteRule ^ %1 [R=301,NE,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]

您也可以将其添加到您页面 HTML 的 <head> 标签下方:

<base href="/" />

这样每个 亲戚 URL 都是从那个基础 URL 解析的,而不是从当前页面的 URL.