简体   繁体   English

在.htaccess文件中操纵PHP响应的标头?

[英]Manipulate Headers of PHP response in .htaccess-file?

Is it possible to add headers (defined in a .htaccess file) to a response generated by PHP? 是否可以将标头(在.htaccess文件中定义)添加到PHP生成的响应中?

I have the following .htaccess file in my that should add a Header TestHeader to each response delivered by my Apache Webserver: 我有以下.htaccess文件,该文件应向我的Apache Web服务器传递的每个响应中添加标头TestHeader

#<IfModule mod_headers.c>
#  Header unset X-Powered-By
  Header add TestHeader "It works."
#</IfModule>

I also have three additional files in that folder: 我在该文件夹中还有三个其他文件:

  1. html.html

     <html>content</html> 
  2. 1.php

     <?php echo "<html>content php</html>"; 
  3. 2.php

     <?php header("TestHeader: Sent from PHP."); echo "<html>content php</html>"; 
    • Requesting html.html returns the header TestHeader: "It works." 请求html.html返回标头TestHeader: "It works."
    • Requesting 1.php does not return header TestHeader 请求1.php 返回头TestHeader
    • Requesting 2.php returns the header TestHeader: "Sent from PHP." 请求2.php将返回标头TestHeader: "Sent from PHP."

Is it somehow possible to manipulate the response header from PHP output using .htaccess directives? 是否可以使用.htaccess指令从PHP输出操作响应标头?

EDIT: PHP runs as FastCGI on the server. 编辑:PHP在服务器上作为FastCGI运行。

You can use SetEnvIf and then add the header accordingly: 您可以使用SetEnvIf,然后相应地添加标题:

SetEnvIf Request_URI "\.php$" phpfile
Header set TestHeader "Sent from PHP" env=phpfile

If the request URL ends with the extension ".php", then SetEnvIf will set a variable "phpfile". 如果请求URL以扩展名“ .php”结尾,则SetEnvIf将设置变量“ phpfile”。 If the variable "phpfile" exists only then TestHeader: Sent from PHP will be sent as a response header. 如果仅存在变量“ phpfile”,则将TestHeader: Sent from PHP作为响应头发送。 You can use this logic for as many extensions or URL patterns as you need. 您可以根据需要将这种逻辑用于任意数量的扩展名或URL模式。

Edit: If the header already exists ie it is sent from PHP, then using Header Set apache will replace it by the new value. 编辑:如果标题已经存在,即它是从PHP发送的,则使用Header Set apache将其替换为新值。

This is likely to be a problem with your Apache version and the fact that PHP runs as FastCGI. 这可能是您的Apache版本和PHP作为FastCGI运行的问题。

In Apache 2.2.X there was a bug: https://bz.apache.org/bugzilla/show_bug.cgi?id=49308 在Apache 2.2.X中存在一个错误: https ://bz.apache.org/bugzilla/show_bug.cgi?id = 49308

I found a couple of other posts that propose to use the always condition to fix the problem: 我发现了其他一些建议使用always条件解决该问题的帖子:

Header always add TestHeader "It works."

Also see: 另请参阅:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM