Laravel 4 - custom 404 error handling only for missing pages

你说的曾经没有我的故事 提交于 2019-12-03 21:36:35

You could not redirect to a different URL, but still display a custom page for 404 errors and send the HTTP 404 Status Code, directly inside App::missing, like this:

App::missing(function() {
    return Response::make(View::make('error404'), 404);
});

This displays the correct view when a page is loaded but forces the browser to throw an error when trying to load a resource, because of the HTTP 404 Status Code.

On Chrome 35, I get this error on the console when trying to load an image in an img tag:

GET http://testing.app:8000/test 404 (Not Found)

I would check to see what the Request wants in the App::missing method. Not sure if this would work right out of the box, but it's a start.

App::missing(function($exception)
{
    if( Request::format() == 'text/html' )
        return Redirect::to('error404', 303)->with(array('error' => array('url' => Request::url())));
}

Edit

Since the code above doesn't do what you want, I revised it to something else. It feels like a hack and I would not recommend using it in production; I would recommend looking for a better way to do this, but I think this will work. (It does for me)

App::missing(function($exception)
{
    $uri = Request::getRequestUri();
    $ext = explode(".", $uri);

    if( preg_match("/(jpg|gif|png|tif)/", end($ext)) !== 1 )
        return Redirect::to('error404', 303)->with(array('error' => array('url' => Request::url())));
});

Part of the reason this is difficult to do is because the application doesn't know what a request string really should return. For example, a request uri of /images/FJB3cB09 could possibly be an image. A uri of /images/my-profile.jpg doesn't necessarily have to return a JPEG image. It can't know what the content type is until after it reads the contents of the file; if there's no file found, then you can't accurately tell what you were trying to access. Make sense?

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