【发布时间】:2018-04-18 01:52:21
【问题描述】:
当我去http://www.example.com/new/index.php/login/
(请注意/index.php/ 作为网址的一部分。)
成功登录后,我会重定向到http://www.example.com/new/welcome/
没错。
但登录屏幕 url 不应包含 /index.php/,因为这是 Silex restapi。
但是当我尝试不使用/index.php/ 登录时
http://www.example.com/new/login/
这次登录后,我被重定向到new/index.php,而不是上次的/welcome/。
请帮忙。
我的代码如下:
索引.php:
$app = Silex\Application;
$app->mount('/login', new Routers\Login());
$app->run();
路由器\Login.php:
namespace Routers;
use Silex\Application;
use Silex\Api\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\Request ;
class Login implements ControllerProviderInterface
{
public function connect(Application $app)
{
// creates a new controller based on the default route
$controllers = $app['controllers_factory'];
$controllers->get('/', 'Controllers\\Login::index');
$controllers->post('/', 'Controllers\\Login::validate');
return $controllers;
}
}
控制器\Login.php:
namespace Controllers;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
class Login {
public function index(Request $request, Application $app)
{
return $app['twig']->render('login.html');
}
public function validate(Request $request, Application $app)
{
// validation goes here
if ( // invalid ) {
return $app['twig']->render('login.html');
} else {
// valid
header("Location: /welcome");
exit;
}
}
}
htaccess:
<IfModule mod_rewrite.c>
RewriteEngine On
# Send would-be 404 requests to Craft
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
RewriteRule (.+) index.php?p=$1 [QSA,L]
</IfModule>
编辑: 我想我发现了问题,登录表单是:
<form method="post" action="index.php">
而不是将数据发布到http://www.example.com/new/login 那么action url必须是怎样的呢?我尝试了 action="/new/login" 但它不起作用。我没有 POST /login 的路线。但这是在 Routers/Login.php 中定义的,那么我为什么要得到这个呢? 请指教。
编辑2: 我如何在我的 Routers\Login.php 中命名路由,因为我正在使用像
这样的挂载的有组织的控制器$controllers->get('/', 'Controllers\\Login::index');
它似乎不接受 bind()?有组织的控制器是否支持命名路由器?
【问题讨论】:
-
你使用twig作为模板引擎吗?此外,您可以使用 RedirectResponse,而不是使用标头位置进行重定向。
-
是的,树枝。请举一个 RedirectResponse 的例子。
-
我建议您在 twig 文档中查看
path(),这样您就可以在您的action="{{ path('login') }}"中使用它并使用正确的路径。 -
我在文档上看不到这样的功能。请给出直接链接。
标签: php .htaccess redirect routing silex