Reputation: 4631
Is it possible to add headers (defined in a .htaccess
file) to a response generated by PHP?
I have the following .htaccess
file in my that should add a Header TestHeader
to each response delivered by my Apache Webserver:
#<IfModule mod_headers.c>
# Header unset X-Powered-By
Header add TestHeader "It works."
#</IfModule>
I also have three additional files in that folder:
html.html
<html>content</html>
1.php
<?php
echo "<html>content php</html>";
2.php
<?php
header("TestHeader: Sent from PHP.");
echo "<html>content php</html>";
html.html
returns the header TestHeader: "It works."
1.php
does not return header TestHeader
2.php
returns the header TestHeader: "Sent from PHP."
Is it somehow possible to manipulate the response header from PHP output using .htaccess
directives?
EDIT: PHP runs as FastCGI
on the server.
Upvotes: 5
Views: 3745
Reputation: 11082
This is likely to be a problem with your Apache version and the fact that PHP runs as FastCGI.
In Apache 2.2.X there was a bug: 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:
Header always add TestHeader "It works."
Also see:
Upvotes: 2
Reputation: 888
You can use SetEnvIf and then add the header accordingly:
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.
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.
Upvotes: 3