【问题标题】:Redirect all request to index.php file in public folder将所有请求重定向到公共文件夹中的 index.php 文件
【发布时间】:2016-10-14 08:01:15
【问题描述】:

我在将所有请求重定向到放置在公共文件夹中的 index.php 文件时遇到问题。

Name_of_app
|-app
|  |--controllers/
|-config/
|  |--db.config
|-public/
|  |--js/
|  |--css/
|  |--index.php
|  |--.htaccess
|-vendor/
|-.htaccess
|-composer.json

有两个 .htaccess 文件, 首先是 Name_of_app/.htaccess 文件,这应该将所有流量重定向到 Name_of_app/public 文件夹

RewriteEngine On

RewriteCond %{REQUEST_URI} !public/
RewriteRule (.*) /public/$1 [L]

其次是 Name_of_app/public/.htaccess 文件,它将所有流量重定向到 /public/index.php 文件

RewriteEngine On

# Some hosts may require you to use the `RewriteBase` directive.
# If you need to use the `RewriteBase` directive, it should be the
# absolute physical path to the directory that contains this htaccess file.
#
# RewriteBase /

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

问题是:
1. 我无法从 url www.name_of_app.com/ 访问 /public/index.php 文件。
2. www.name_of_app.com/index.php显示/public/index.php page not found错误

帮我解决这个问题。谢谢。

【问题讨论】:

  • 为什么要将规则集拆分为两个单独的文件?这只会使事情变得更复杂,并进一步减慢 http 服务器的速度。整合规则。
  • 老实说,我会将DOCROOT 设置为public 文件夹。
  • “我无法访问”实际上是什么意思? 要准确。 “显示...页面未找到错误”意味着什么确切地? _该错误在哪里显示?
  • @arkascha url www.name _of_app/ 显示“在此服务器上找不到请求的 URL /public/。”
  • 对不起,但我实际上对此表示怀疑。这意味着内部重写过程的细节会暴露在外部,这听起来不太可能。我的印象是,您在现实世界中的问题实际上与您在此处发布的内容不同。

标签: php apache .htaccess redirect mod-rewrite


【解决方案1】:

删除/public/.htaccess。在/.htaccess 中输入:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(?!public/(?:index\.php)?$) public/index.php [L]

然后,您的 PHP 应用程序应该解析 $_SERVER['REQUEST_URI'] 以查看发送时的 URL。使用其中的任何查询覆盖$_GET 的内容,然后从$_GET 重新生成$_REQUEST,然后再生成$_POST。一个简单的方法是这样的:

$url_path = explode($_SERVER['REQUEST_URI'], '?', 2);
if (isset($url_path[1])) {
    parse_str($url_path[1], $_GET);
}
else {
    $_GET = [];
}
$url_path = (string) substr($url_path[0], 1);// ignore leading '/'

你可能不需要RewriteBase

【讨论】:

    【解决方案2】:

    为 Name_of_app/public/.htaccess 尝试以下代码

    DirectoryIndex index.php
    
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>
    
    <IfModule !mod_rewrite.c>
        <IfModule mod_alias.c>
            RedirectMatch 302 ^/$ /index.php/
        </IfModule>
    </IfModule>
    

    【讨论】:

    • "在此服务器上找不到请求的 URL /public/。"访问 localhost/name_of_app/ 时出错
    • 这样使用会产生什么样的结果,对于Name_of_app/.htaccess RewriteEngine On RewriteCond %{REQUEST_URI} !public/ RewriteRule (.*) /public/index.php$1 [L]
    猜你喜欢
    • 2013-10-26
    • 2012-12-07
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多