【问题标题】:How can I force all URI requests to index.php?如何强制所有 URI 请求到 index.php?
【发布时间】:2020-01-28 07:41:47
【问题描述】:

在我的index.php(在我的项目根目录中)中,我有一个基本的路由系统,它可以抓取 url(使用 $_SERVER[‘REQUEST_URI])并调用正确的“控制器”,然后调用正确的“视图”(所以,非常基本的MVC的实现)。我的index.php 中的内容如下所示:

$router= Router::load('Routes.php');
$uri=trim($_SERVER['REQUEST_URI'],'/'); 
require $router->direct($uri);

问题是,我似乎无法将所有请求都发送到index.php。 显然,如果您转到localhost/myproject/,您将到达index.php(因此将调用适当的控制器),但是我想要的是,即使您键入localhost/myproject/contact,首先要直接转到index.php。这样index.php 就可以为你处理路由了。

【问题讨论】:

标签: php laravel apache cakephp-routing


【解决方案1】:

如果您使用的是 apache,则可以使用 .htaccess 文件重定向 index.php 文件中的每个请求:

RewriteEngine On

RewriteRule ^/index\.php$ - [L,NC]

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

如果您使用的是 nginx 服务器,您可以在 .conf 文件中使用此代码将所有请求重定向到 index.php 文件:

location / {
    try_files $uri $uri/ /index.php;
}

希望对你有帮助

【讨论】:

  • 我是将 .htaccess 文件添加到我的本地主机根目录 (localhost) 还是添加到“我的项目”根文件夹,在这种情况下是 (localhost/myproject/)?
  • 是的,如果您使用的是 apache,您必须将 .htaccess 放在您的根目录中
猜你喜欢
  • 2016-11-30
  • 2016-04-15
  • 2021-09-02
  • 2014-05-24
  • 1970-01-01
  • 2018-11-29
  • 1970-01-01
  • 2015-04-10
  • 1970-01-01
相关资源
最近更新 更多