【问题标题】:How to use .htaccess to redirect while maintaining the original URL如何在保留原始 URL 的同时使用 .htaccess 进行重定向
【发布时间】:2019-04-08 16:13:49
【问题描述】:

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

所以如果用户去:

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

它会将它们重定向回:

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

但原来的 URL 输入不会改变。

【问题讨论】:

    标签: .htaccess mod-rewrite url-redirection url-masking


    【解决方案1】:

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

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

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

    【讨论】:

    • 这很好用。我删除了文件夹 1 并添加到文件夹 1 内的 .htaccess 文件中:RewriteEngine on RewriteCond %{REQUEST_URI} !^index\.php$ [NC] RewriteRule ^.+$ index.php [L]
    【解决方案2】:

    你可以做:

    RedirectMatch 301 ^https://example.com/folder1/ https://example.com/folder1/index.php
    

    这允许您从模式中的第一个 url 重定向到 第二个

    【讨论】:

    • 有无数个可能的 URL 可以输入,我希望原始 URL 输入保留在地址栏中。
    • 您的意思是应该重定向以example.com 开头的网址?这是真的吗?
    • 我想要在 example.com/folder1/ 之后重定向到 example.com/folder1/index.php
    猜你喜欢
    • 2015-07-27
    • 1970-01-01
    • 2019-11-17
    • 2011-01-24
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 2011-08-29
    • 2013-09-05
    相关资源
    最近更新 更多