如何使用Apache Perl处理程序重定向?

时间:2017-01-26 00:17:30

标签: apache perl redirect cgi cgi-bin

我有一个Apache Handler,它将扩展名.redir设置为Perl脚本。代码如下:

Action redir-url /cgi-bin/redir.pl
AddHandler redir-url .redir

该脚本应该只是将用户重定向到.redir文件中包含的页面。例如:

so.redir

http://stackoverflow.com/

如果用户访问http://example.com/so.redir,他们将被重定向到http://stackoverflow.com/

我当前的代码如下,虽然它返回错误500,可能完全关闭:

#!/usr/bin/perl
use strict;
use warnings;

use Path::Class;
use autodie;

my $file = file($ENV{'PATH_TRANSLATED'});

my $file_handle = $file->openw();

my @list = ('a', 'list', 'of', 'lines');

foreach my $line ( @list ) {
    # Add the line to the file
    $file_handle->print("Location: ".$line."\n\n");
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

回到cgi-days我们曾经有一个小的子程序进行重定向:

sub redirect_url {
    my ($url, %params) = @_;

    $params{Location} = $url;

    if ( ($ENV{'HTTP_USER_AGENT'}=~m|Mozilla\/4\.|)
        && !($ENV{'HTTP_USER_AGENT'}=~m|MSIE|) ) {

        # handle redirects on netscape 4.x
        $params{Status} = '303 See Other'
            unless exists $params{Status};
        $params{'Content-Type'} = 'text/html; charset=utf-8'
            unless exists $params{'Content-Type'};
        $params{Content} =<<EOF;
<html>
  <head>
    <script language="JavaScript"><!--
location.href = "$params{Location}";
//--></script>
  </head>
  <body bgcolor="#FFFFFF">
    <a href="$params{Location}">Redirect</a>
  </body>
EOF
    }
    else {
            $params{Status} = '301 Moved Permanently'
            unless exists $params{Status};
        $params{'Content-Type'} = 'text/plain; charset=utf-8'
            unless exists $params{'Content-Type'};
    }

    $params{Expires} = 'Fri, 19 May 1996 00:00:00 GMT'
        unless exists $params{Expires};
    $params{Pragma} = 'no-cache'
        unless exists $params{Pragma};
    $params{'Cache-Control'} = 'no-cache'
        unless exists $params{'Cache-Control'};

    my $content = exists $params{Content}
        ? $params{Content} : $params{Status};
    delete $params{Content};

    while (my ($key, $value) = each %params) {
        print "$key: $value\n";
    }
    print "\n";
    print $content;

    exit 0;
}

所以,如果我得到你的代码的其余部分:

use strict;
my $file = $ENV{'PATH_TRANSLATED'};
open (my $fh, '<', $file) or die 'cant open';
my $url = <$fh>;
chomp($url);
redirect_url($url);

可以胜任。