【问题标题】:How to write .htaccess to forward all requests to index.php in whatever subfolder they were made如何编写 .htaccess 将所有请求转发到 index.php 中的任何子文件夹
【发布时间】:2020-05-28 14:38:55
【问题描述】:

我希望将每个请求转发到 index.php,但要注意请求是在哪个子文件夹中发出的。我可以让它们都转到根 index.php,但不能转到特定子文件夹中的 index.php。

示例:
site.com/testurl > site.com/index.php
site.com/admin/testurl > site.com/admin/index.php
site.com/randomname/randomname > site.com/randomname/index.php

我不想硬编码任何子文件夹以使其保持动态。

目前,我将此作为我的 .htaccess 文件:

DirectoryIndex index.php

# enable apache rewrite engine
RewriteEngine on

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1%{REQUEST_URI} [R=301,QSA,NC,L]

# Deliver the folder or file directly if it exists on the server
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Push every request to index.php
RewriteRule ^(.*)$ index.php [QSA]

额外功劳(不确定 .htaccess 是否可行): 让它知道 index.php 是否在子目录中,如果没有,则回退到根 index.php

【问题讨论】:

    标签: php .htaccess


    【解决方案1】:
    # Determines whether the request doesn't end with index.php:
    RewriteCond %{REQUEST_URI} !/index.php$
    
    # Redirect to the requested path, followed by index.php:
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)/(.*)$    /$1/index.php [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !/index.php$
    RewriteRule ^(.*) /index.php [L]
    

    【讨论】:

    • 感谢您的发帖。如果我将您的代码放入并用您的替换我的最后一个重写规则,那么它适用于子域,但不再适用于主域。两个规则一起似乎没有按预期工作。
    • 对了,忘记root了:需要加RewriteRule ^([^\/]*)$ /index.php [L]
    • 添加它会导致 500 服务器错误。替换它仍然只适用于子文件夹。
    • @DavidEdwards 我已经更新了我的答案并测试了它在这些情况下是否有效:site.com/foo => site.com/index.php, site.com/foo/bar => site.com/foo/index.phpsite.com/foo/bar/baz => @987654328 @.
    • 一个小问题......它忽略了实际存在的文件......所以 site.com/foo/bar.php 不起作用
    猜你喜欢
    • 2017-12-24
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    • 2013-10-26
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    相关资源
    最近更新 更多