Perl 重写旧 URL 以利于 seo

问题描述 投票:0回答:2

我正在尝试修复所有 .html 请求中包含错误字符的旧 URL

我想用破折号替换以下实例(

-
):

  • 空间
  • 科马斯
  • 加号
  • 括号
  • 撇号
  • 双破折号加单破折号
  • 然后全部大写和小写

以下内容已实施,但在服务器上不起作用

我重写了 nginx 正在使用的 perl 片段,如下所示:

perl_set $old_uri 'sub {
my $r = shift;
my $uri = $r->uri;

$uri = lc $uri;
$uri =~ s/[+, ()\']/-/g;
$uri =~ s/--+/-/g;

return $uri;
}';

这会将所有内容切换为小写,将请求的符号转换为破折号,然后将一行中的多个破折号压缩为一个

Perl 规则是

    perl_set $old_uri 'sub {
    my $r = shift;
    my $uri = $r->uri;

    $uri = lc $uri; # Upper to lower
    $uri =~ s/[^a-z0-9-.\/]/-/g;
    $uri =~ s/--+/-/g; # turn double -- to -

    return $uri;
   }';

调用此的位置块是

  location ~ [^a-z0-9-.\/].*.html {
        rewrite ^ $old_uri permanent;
    }

如果我需要提供更多信息,请告诉我

regex perl nginx url-rewriting seo
2个回答
0
投票

您可以将任何特殊字符替换为破折号/连字符

$url=~ s/\W+/-/g;

0
投票

哎哟!

您的第一个解决方案已经非常接近了。 看起来唯一的问题是您需要转义字符类中的特殊字符。 所有这些都是特殊字符,如果您想按字面处理它们,则需要转义 (\)。 这里有一个解决方案

#!/usr/bin/perl -w

my $url = qq"http://space /comma,/plus+/parentheses()/apostrophes'/doubleDash--/UPPERCASE/";
print "Original URL:\n$url\n\n";

#fix uppercase first
$url = lc $url;

#regular expression to replace various characters with dash
#probably a character class will work best, you will have to
#escape all the characters (\) because they are all special characters
#that is what is wrong with the original regex

$url =~ s/([ \,\+\(\)\'])|(--)/-/g;

print "Fixed URL:\n$url\n\n";

输出看起来像这样

$ perl fixUrl.pl
Original URL:
http://space /comma,/plus+/parentheses()/apostrophes'/doubleDash--/UPPERCASE/

Fixed URL:
http://space-/comma-/plus-/parentheses--/apostrophes-/doubledash-/uppercase/

因此要纠正第一个程序,只需替换这两个正则表达式即可

$uri =~ s/[+, ()\']/-/g;
$uri =~ s/--+/-/g;

有了这个

$url =~ s/([ \,\+\(\)\'])|(--)/-/g;

应该是 $uri 还是 $url? 只要保持一致就应该没关系。 我将两个正则表达式合并为一个,这样您就不必使用或 (|) 字符运行其中两个正则表达式。 如果需要匹配两个以上的破折号,请将

(--)
部分替换为
(--+)

祝你好运!

© www.soinside.com 2019 - 2024. All rights reserved.