首页 > 解决方案 > 如何在保留原始 URL 的同时使用 .htaccess 进行重定向

问题描述

我正在尝试使用 .htacces 文件将目录中的任何文件或子文件夹重定向到一个文件,同时仍保留原始 URL 输入。

因此,如果用户访问:

https://example.com/folder1/folder2/folder3/
or
https://example.com/folder1/folder2/file.php

它会将它们重定向回:

https://example.com/folder1/index.php

但原始 URL 输入不会改变。

标签: .htaccessmod-rewriteurl-redirectionurl-masking

解决方案


您可以使用RewriteRule. 在文档根目录的 htaccess 中添加以下规则:

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/folder1/index\.php$ [NC]
RewriteRule ^folder1/.+$ /folder1/index.php [L]

这将重定向/folder1/foo/bar/folder1/index.php而不更改浏览器中的 url。
以上RewriteCond确保您不会重写/folder1/index.php自身 ( /folder1/index.php),否则该规则可能会导致无限循环错误。


推荐阅读