将所有请求重定向到公用文件夹中的index.php文件

时间:2016-10-14 08:01:16

标签: php apache .htaccess redirect mod-rewrite

我在将所有请求重定向到放在公共文件夹中的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.我无法从网址www.name_of_app.com/访问/public/index.php文件 2. www.name_of_app.com/index.php显示未找到/public/index.php页面错误

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

2 个答案:

答案 0 :(得分: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的内容,然后从$_REQUEST然后$_GET重新生成$_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

答案 1 :(得分:0)

为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>