当我导航到 /public/index.php/main/anything 时,我收到此错误:
404 Controller or its method is not found: {0}::{1}
我有一个基于文档中示例的 codeigniter 4 项目(https://codeigniter4.github.io/userguide/tutorial/news_section.html)
我添加了这 3 条路线:
$routes->get('main/(:any)','main/Main::view/$1');
$routes->get('main', 'main/Main::index');
$routes->get('/', 'Home::index');
这里的其他设置:
$routes->setDefaultNamespace('App\Controllers');
$routes->setDefaultController('Home');
$routes->setDefaultMethod('index');
$routes->setTranslateURIDashes(false);
$routes->set404Override();
$routes->setAutoRoute(true);
当我导航到 /public/index.php/main 时,我得到了很好的索引结果。
我试过了:
main/Main::view
不超过 1 美元,它工作正常。
但是,一旦我添加 $1,我就会收到上述 404 错误。我也试过:segment
同样的结果:404错误。
我什至从来没有进入视图方法,我试图回应一些东西。
我需要代码的最后一段,因为我需要将它传递给我的模型以进行进一步处理。
此外,很高兴知道如何设置路由以摆脱 public/index.php 部分而不产生任何安全问题。
public/.htaccess 文件如下所示:
Options All -Indexes
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
RewriteRule ^(.*)/$ /$1 [L,R=301]
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
<IfModule !mod_rewrite.c>
ErrorDocument 404 index.php
</IfModule>
ServerSignature Off
<Files ~ "\.(env|json|config.js|md|gitignore|gitattributes|lock)$">
Order allow,deny
Deny from all
</Files>
更新:我已经重新创建了演示项目,只要 Main.php 文件位于 Controllers 文件夹中,上述内容就可以工作。我的位于一个名为 Controllers/main 的子文件夹中,并且相应地设置了路由文件。因此,此代码不适用于子文件夹,如果我们想保持代码井井有条,这很糟糕。所以我欢迎解决方案。谢谢你。