-
Notifications
You must be signed in to change notification settings - Fork 4
/
viewer.psgi
91 lines (68 loc) · 2.14 KB
/
viewer.psgi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/perl
use warnings;
use strict;
use feature ':5.10';
use Log::Dispatch;
use Plack::Builder;
use DateTime;
my $app = Plack::App::IndexFile->new({ root => './public_html' })->to_app;
# For Plack::Middleware::AccessLog
my $logger = Log::Dispatch->new(
outputs => [
[ 'File', min_level => 'debug',
filename => 'logs/hits.' . DateTime->now->ymd('-') . '.log' ],
[ 'Screen', min_level => 'warning' ],
],
);
my $log_cb = sub {
my $line = shift;
# Exclude the 4 extra, UA-less requests when the ESI layer
# GETs (head|header|nav|footer).html
return if $line =~ m/"-" "-"/;
my $level = 'debug';
if (
($line =~ /HTTP\/1.1" (?:4\d\d|5\d\d) /)
and ($line !~ /Googlebot|bingbot|baidu|ahrefs|YandexBot/)
) {
$level = 'warning';
}
$logger->log( level => $level, message => $line );
};
# For Plack::Middleware::Rewrite (using to redirect)
my $spellitright = sub {
my $env = shift;
my $host = $env->{HTTP_HOST} || $env->{SERVER_NAME};
return undef unless $host; # effective pass-through
if ($host =~ s/judgemental\.org\.uk/judgmental\.org\.uk/) {
my $redirect = 'http://' . $host . $env->{REQUEST_URI};
my $message =<<"END";
The proper spelling is 'judgmental.org.uk' (no 'e' after the 'g').<br />
You should be redirected there shortly.<br />
If not, please <a href="$redirect">click here</a>.
END
return [
'301',
[ Location => $redirect ],
[ $message ],
];
}
# Didn't see the errant 'e' - continue as normal
return undef;
};
return builder {
enable 'Rewrite', rules => $spellitright;
enable 'ESI';
enable 'AccessLog', logger => $log_cb;
# enable 'Debug';
$app;
};
package Plack::App::IndexFile;
use parent 'Plack::App::File';
sub locate_file
{
my ($self, $env) = @_;
my $path = $env->{PATH_INFO} || '';
return $self->SUPER::locate_file( $env ) unless $path && $path !~ m{\.[[:alnum:]]{2,4}$};
$env->{PATH_INFO} .= ( substr( $env->{PATH_INFO}, -1 ) eq '/' ? '' : '/' ) . 'index.html';
return $self->SUPER::locate_file( $env );
}