sub abs_url { my ( $relative, $base ) = @_; return $relative if $relative =~ m{ \A http:// }ix; my ( $host, $hostrelative_abs ) = $base =~ m{ \A http:// # skip scheme ([^/]*) # capture hostname /* # skip front slashes (.*?) # capture everything that follows, but [^/]* # leave out the optional final non-directory component \z }ix; $hostrelative_abs = '' if $relative =~ m!^/!; my $abs_url = join '/', $host, $hostrelative_abs, $relative; # replace '//' or '/./' with '/' 1 while $abs_url =~ s{ / \.? (?=/|\z) }{}x; # remove '/foo/..' (but be careful to skip '/../..') 1 while $abs_url =~ s{ / (?!\.\.) [^/]+ / \.\. (?=/|\z) }{}x; return "http://$abs_url"; } #### use Test::More; my @test = qw( /foo/bar.gif http://www.example.com/baz/quux/ http://www.example.com/foo/bar.gif foo/bar.gif http://www.example.com/baz/quux/ http://www.example.com/baz/quux/foo/bar.gif ../../bar.gif http://www.example.com/baz/quux/ http://www.example.com/bar.gif foo/bar.gif http://www.example.com/baz/quux http://www.example.com/baz/foo/bar.gif ../foo/bar.gif http://www.example.com/baz/quux http://www.example.com/foo/bar.gif ../../foo/bar.gif http://www.example.com/baz/quux/qux http://www.example.com/foo/bar.gif ); plan tests => @test / 3; do { is abs_url( $test[0], $test[1] ), $test[2]; splice @test, 0, 3 } while @test;