在.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 Webserver提供的每个响应添加一个Header 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.HTML

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

    1.PHP

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

    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:“它有效。”
    • Requesting 1.php does not return header TestHeader
    • 请求1.php不会返回标头TestHeader
    • Requesting 2.php returns the header TestHeader: "Sent from PHP."
    • 请求2.php返回标题TestHeader:“从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运行。

2 个解决方案

#1


2  

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:

另见:

#2


3  

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". If the variable "phpfile" exists only then TestHeader: Sent from PHP will be sent as a response header. You can use this logic for as many extensions or URL patterns as you need.

如果请求URL以扩展名“.php”结尾,则SetEnvIf将设置变量“phpfile”。如果变量“phpfile”仅存在,则TestHeader:从PHP发送将作为响应头发送。您可以根据需要将此逻辑用于尽可能多的扩展或URL模式。

Edit: If the header already exists i.e. it is sent from PHP, then using Header Set apache will replace it by the new value.

编辑:如果标头已经存在,即它是从PHP发送的,那么使用Header Set apache将用新值替换它。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/07/01/f284c34c59b2b858c5c8f367efad28d4.html



 
  © 2014-2022 ITdaan.com 联系我们: