通过 Apache 发送自定义 HTTP 标头PHP 在一个宁静的网络服务中
我正在编写一个 RESTful Web 服务,它在成功/不成功的操作时返回自定义/现有的 HTTP 标头。
例如,如果身份验证失败,将发送 401 HTTP 标头等。
我已通过 PHP header() 函数发送标头,但当然不会将其发送回调用者。我真正需要做的是通过 Apache(而不是 PHP)将标头发送回调用脚本。我正在对网络服务中收到的数据进行某些检查,然后发送标头。我该如何通过 Apache 推送这些标头呢?
谢谢!
I'm writing a RESTful webservice that returns custom/existing HTTP headers on successful/unsuccessful operations.
For eg., if the authentication fails, the 401 HTTP header will be sent, etc.
I've sent the headers via the PHP header() function, but of course that is not sent back to the caller. What I really need to do is to send headers via Apache, instead of PHP, back to the calling script. I'm carrying out certain checks for the data that I receive in my webservice, and then sending the headers. How would I go about pushing these headers via Apache instead?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是什么让你如此确定?我倾向于认为你在某个地方做错了什么......
What makes you so sure? I'm inclined to think that you're doing something wrong somewhere...
我可能会使用 PHP 而不是 Apache 来完成此操作,但这只是我自己的偏好。如果对
header()
的调用不起作用,可能是因为在调用header()
之前,PHP 标记之外的某个位置有空格。请注意 PHP 手册中的这一点:如果您必须使用 Apache 执行此操作,则 mod_headers 似乎不适合。 mod_headers 只能根据请求是否成功(2xx)或任何请求的条件设置标头。请参阅标头指令。
相反,我认为可以通过结合使用 mod_rewrite 和mod_asis。我对此没有特定的“秘诀”,但想法是检查请求是否已通过 mod_rewrite 授权,如果未授权,则将请求 URI 重写/重定向到包含以下内容的 .asis 文档:您要发回的标头信息。
I would probably do this with PHP and not Apache, but that is just my own preference. If the call to
header()
isn't working, it's likely because you have whitespace outside of PHP tags somewhere before your call toheader()
. Take note of this in the PHP manual:If you must do this with Apache, mod_headers doesn't seem suited. mod_headers can only set headers based on conditions of whether a request is successful (2xx) or for any request. See Header directive.
Instead, I think it could be done by a combination of using mod_rewrite and mod_asis. I don't have a particular "recipe" for this, but the idea would be to check to see if a request is authorized with mod_rewrite, and if it's not authorized, rewrite/redirect the request URI to an .asis document that contains the header info that you want to send back.
想出了解决办法。将“true”作为第二个参数传递给 header(),将实际状态代码作为第三个参数传递。例如, header('HTTP 1.1/400 错误请求', true, 400)。这将强制向调用者发送 400 状态代码。我至少在 LiveHTTPHeaders 中检查过这一点,所以它可能有效。我只需要通过curl 调用它即可完全确定。
Figured out the solution. Pass in 'true' as the second argument to header(), and the actual status code as the third argument. For eg., header('HTTP 1.1/400 Bad Request', true, 400). This will force the 400 status code to the caller. I've checked this atleast in LiveHTTPHeaders, so it might work. I'll just need to call this via curl to be completely sure.