0

我在设置 cookie 然后在 mod_perl 下重定向时遇到了一个有趣的问题。到目前为止,我有一个常规的 cgi 环境,设置 cookie/redirect 从来都不是问题;一切都按预期进行。然而,当我打开 mod_perl 时,我得到一个状态 200 和一个带有重定向 url 的 html 正文。cookie 总是放在标题之后和文档正文之前,即使我在重定向之前打印它。我将脚本精简为基本内容,以便您了解我的意思:

#!/usr/local/bin/perl

use strict;
use warnings;

use CGI;

my $cgi = new CGI;

my $cookie = CGI::cookie(
  '-name'     => 'joe',
  '-value'    => 'fred',
  '-path'     => '/cgi-bin',
  '-httponly' => 1,
);
print "Set-Cookie: $cookie\n";

print $cgi->redirect(-uri => 'http://example.com/cgi-bin/joe.cgi', -status => 303);

当我在常规 CGI 下使用 curl 进行测试时,我得到(为简洁起见,域名被替换和剪断):

< HTTP/1.1 303 See Other
< Date: Tue, 23 Oct 2012 16:26:55 GMT
< Server: Apache/2.2.22 (Ubuntu)
< Set-Cookie: joe=fred; path=/cgi-bin; HttpOnly
< Location: http://example.com/cgi-bin/joe.cgi
< Content-Length: 0

...这是我所期望的。当我在 mod_perl 下测试它时,我得到:

< HTTP/1.1 200 OK
< Date: Tue, 23 Oct 2012 16:26:38 GMT
< Server: Apache/2.2.22 (Ubuntu)
< Location: http://example.com/cgi-bin/joe.cgi
< Transfer-Encoding: chunked
<
Set-Cookie: joe=fred; path=/cgi-bin; HttpOnly
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>200 OK</title>
</head><body>
<h1>OK</h1>
<p>The answer to your request is located <a href="http://example.com/cgi-bin/joe.cgi">here</a>.</p>
<hr>
<address>Apache/2.2.22 (Ubuntu) Server at example.com Port 80</address>
</body></html>

我在日志中没有收到任何警告。知道为什么 mod_perl 决定以这种奇怪的方式处理这个重定向吗?

4

2 回答 2

1

IIRC 将其在CGI 中解释为 mod_perl 移植。mod_perl 编码指南

$cgi->redirect( -cookie => $cookie, ... ) 基本上,如果您使用Mixing$cgi->header和 print "header\n" 不会在 mod_perl 下可靠地工作,它会按照您的预期工作,选择一个或另一个

于 2012-10-27T03:11:39.963 回答
1

实际上为我解决了所有问题的是:

my $r = Apache2::RequestUtil->request;
$r->err_headers_out->add('Set-Cookie' => $cookie);

...用于我的 cookie 处理。如果您决定稍后重定向,这可以确保 cookie 将起作用。

我试图避免用 mod_perl 污染我的纯 cgi 脚本,这样我就可以来回切换,但对此有所妥协。所有其他标头处理现在都可以正常工作。

于 2012-10-31T13:49:25.293 回答