【问题标题】:mod_rewrite redirect url if no file found to main page如果没有找到到主页的文件,则 mod_rewrite 重定向 url
【发布时间】:2014-02-26 03:31:57
【问题描述】:

我希望能够在没有 .php、.html 等的情况下访问我的脚本,所以我已经写了

RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}\.php -f
RewriteRule ^(.*)$ $1.php
##same for other extensions

在我的 .htaccess 文件中(注意:此文件不在根路径中),但我还想将每个不正确的请求重定向到我的主页,以便重写 www.mysite.com/dir/incorrect到 www.mysite.com/dir/。

但我的第一次尝试(RewriteCond 之后的 RewriteRule ^ / [R])将我重定向到 www.mysite.com/,我对 RewriteBase(RewriteBase 和 RewriteBase /)的实验没有奏效,我还注意到许多类似的脚本重定向到 www .mysite.com/dir/index.php(在我的情况下为 www.mysite.com/dir/index),但我真的想重定向到 www.mysite.com/dir/。有什么方法可以实现吗?

【问题讨论】:

    标签: apache .htaccess mod-rewrite redirect


    【解决方案1】:

    这样吧:

    RewriteEngine on
    
    # see if .php is found
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}\.php -f
    RewriteRule ^(.*)$ $1.php [L]
    
    # determine DIR_BASE dynamically
    RewriteCond %{REQUEST_URI}::$1 ^(.*?/)(.*)::\2$
    RewriteRule ^(.*)$ - [E=DIR_BASE:%1]
    
    # if not found redirect to %{ENV:DIR_BASE}
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ %{ENV:DIR_BASE} [L,R]
    

    【讨论】:

    • 谢谢,但我仍然有 RewriteRule ^ / [L, R] 重定向到 www.mysite.com/ 而不是 www.mysite.com/dir/ 的问题(/dir 是目录.htaccess 文件是)
    • 哦,也可以这样做,但问题中没有提到。我会在几分钟内更新答案。
    • 非常感谢,最近几天这些问题让我很生气,感谢您的回答
    猜你喜欢
    • 1970-01-01
    • 2019-05-05
    • 2012-10-09
    • 2020-05-20
    • 2018-03-20
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多