Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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:

  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."
    • Requesting 1.php does not return header TestHeader
    • Requesting 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.

like image 552
Edward Avatar asked Jul 01 '16 12:07

Edward


1 Answers

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.

like image 131
nidhi Avatar answered Sep 22 '22 20:09

nidhi