Laravel 4 - custom 404 error handling only for missing pages

倾然丶 夕夏残阳落幕 提交于 2019-12-05 07:15:37

问题


In Laravel 4.1 I want to redirect the user to my customised 404 page if the page is not exists. That's easy because I already have this:

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

But the problem is that if any linked file (image, js, css, etc.) is missing on the page I don't get 404 error for that file, but this is showing on console:

Resource interpreted as Image but transferred with MIME type text/html: "...

So the question is: How can I drop 404 only if a page is missing and leave the default error handling for the rest (images, other files, etc.)?

Thanks in advance!


回答1:


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)



回答2:


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?



来源:https://stackoverflow.com/questions/24185735/laravel-4-custom-404-error-handling-only-for-missing-pages

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