Laravel 3 HTTP and HTTPS routes

女生的网名这么多〃 提交于 2019-12-21 23:14:14

问题


I have the following code:

Route::get('/',   function()
{
    return 'non secure page';
});
Route::get('/',  array('https' => true, function()
{
    return 'secure page';
}));

What I expected to happen is that these two routes would be treated differently. The first is for http://example.com requests and the second for https://example.com. Respectively, these pages should show the text 'non secure page' and 'secure page'. What actually happens is that both show the text 'secure page'. This must mean that both routes are treated the same i.e. it doesn't matter if the request was over https or http - the same route is triggered.

I know I can resolve my issue by using if (Request::secure()){ //routes }; but that then leads me to the question what use are the HTTPS secure routes in laravel? What do they achieve and when should they be used?

I've looked at the docs, but it's not clear to me what is supposed to happen.


回答1:


The documentation says:

When defining routes, you may use the "https" attribute to indicate that the HTTPS protocol should be used when generating a URL or Redirect to that route.

"https" and ::secure() are only used when generating URLs to routes, they're not used to provide https-only routes. You could write a filter to protect against non-HTTPS routes (example below). Or if you want to prevent any non-HTTPS access to your entire domain then you should reconfigure your server, rather than do this in PHP.

Route::filter('https', function() {
    if (!Request::secure()) return Response::error(404);
});

Alternative filter response:

Route::filter('https', function() {
    if (!Request::secure()) return Redirect::to_secure(URI::current());
});

References:

  1. http://laravel.com/docs/routing#https-routes
  2. http://laravel.com/docs/routing#filters



回答2:


The problem is not related to HTTPS.

The documentation says,

Note: Routes are evaluated in the order that they are registered, so register any "catch-all" routes at the bottom of your routes.php file.

It means that your

Route::get('/',  array('https' => true, function()
{
    return 'secure page';
}));

is over-writing

Route::get('/',   function()
{
    return 'non secure page';
});

I was actually lead here by Spark from laravel.io and I thought I would clarify the doubt anyhow.

Regards



来源:https://stackoverflow.com/questions/15435212/laravel-3-http-and-https-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!