使URL标准化

时间:2015-07-27 02:39:46

标签: perl

我已经全面了解了Perl中使URL标准化的方法。换句话说,我试图找到一种方法来检查然后将URL格式example.org,www.example.org或http://example.org更改为标准格式http://www.example.org,无论如何域名。任何建议将不胜感激。

2 个答案:

答案 0 :(得分:1)

您可以按照以下方式自行规范化:

#!/usr/bin/env perl

my $host = 'example.org';
my $canonical = 'http://www.example.org';

for ( 'example.org',
      'www.example.org',
      'http://example.org',
      'example.org/foo/bar?baz=123',
      'www.example.org/foo/bar?baz=123',
      'http://example.org/foo/bar?baz=123',
    ) {

    # Anything followed by 'example.org' followed by anything
    my ($path) = m|^.*?$host(.*)$|;
    my $canonical_path = join '', $canonical, $path || '';
    print sprintf("% 40s => %s\n", $_, $canonical_path);
}

哪个输出:

                       example.org => http://www.example.org
                   www.example.org => http://www.example.org
                http://example.org => http://www.example.org
       example.org/foo/bar?baz=123 => http://www.example.org/foo/bar?baz=123
   www.example.org/foo/bar?baz=123 => http://www.example.org/foo/bar?baz=123
http://example.org/foo/bar?baz=123 => http://www.example.org/foo/bar?baz=123

答案 1 :(得分:0)

您可以将以下内容放在每个网站的.htaccess文件中。

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\.

RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

它会将(www)非www域重定向到www。