I’ve recently moved to a framework with a routing system where you specify routes for different request methods. I hadn’t anticipated receiving HEAD requests, so they’re unhandled and returning a 405.
My understanding is that it’s a bot or something that just wants to see the headers. Does that mean that I should handle the page as normal but not return output? Or just handle it as normal? Or leave it as a 405?
I think HEAD requests should receive proper response, too. The reason behind HEAD is if a user agent wants to receive only headers without the body so if you respond to GET then you should also respond to HEAD. Especially that it is a sign of good manners for the user agent to send HEAD instead of GET because this way they inform the server (you) that they don’t need the body and the server can save resources and not generate the body at all. You should not punish the requester for being kind by blocking him!
By default, PHP handles HEAD the same as GET executing the whole script and then the server just sends back the headers. You need to detect HEAD on your own if you want to skip generating content and frameworks may have mechanisms to handle them specially.
I suspect it is not good behaviour if a framework rejects HEAD requests by default. Whenever GET is allowed, HEAD should be allowed, too. I don’t know which framework you use but I’ve tried Silex and it is handling HEAD the same way as GET.
So it would be good practice to accept HEAD requests, and simply not serve the content (but still serve the headers)?
Yes. Ideally, you would detect a HEAD request, only generate the headers and send them with empty body but I don’t think it’s worth it in most cases. Usually, HEAD requests are so rare in comparison that they don’t add any significant load on the server so I don’t handle them in any special way and let my application generate the whole page like for GET requests. I don’t have to do anything then because the server will discard the body and send only the headers to the requester.
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.