Oded
Oded

Reputation: 664

adding a response header to 302 response using perl

i am trying to write a perl page that returns an http 302 response to a different location and adds a custom header to that response. so my desired http response should be something like this:

HTTP/1.1 302 Moved
Date: Sun, 15 Apr 2012 10:59:02 GMT
Server: Apache
Location: http://www.google.com
Content-Length: 396
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=iso-8859-1
CUSTOM_HEADER: CUSTOM_VALUE

i tried using CGI:

#!/bin/perl

use strict;
use APR::Request::Apache2;
my $r = shift;
$r->content_type('text/html; charset=utf-8');
$r->headers_out()->add("CUSTOM_HEADER", "CUSTOM_VALUE");
$r->headers_out()->add("Location", "http://www.google.com");
$r->status(302);

and i do get 302 response to google but no CUSTOM_HEADER. once i change the status to 200 by $r->status(200); i do get the CUSTOM_HEADER. so whats up with this behavior ? how can i add my header to the 302 response ?

Upvotes: 0

Views: 1914

Answers (2)

mcsi
mcsi

Reputation: 359

You should use err_headers_out(). These will be printed even on errors and redirects.

Upvotes: 2

Ωmega
Ωmega

Reputation: 43673

Use $r->err_headers_out->set or $r->err_headers_out->add

my $r = shift;

$r->content_type('text/html; charset=utf-8');
$r->err_headers_out->set(Location => "http://www.google.com");
$r->status(302);

Upvotes: 2

Related Questions