支持模式

时间:2018-01-03 12:37:38

标签: .htaccess

我有这种网址格式:

https://www.example.com/shows/my_personal_show_2.0_34565.htm

如果尾部编号是数据库引用,我需要将其重写为:

https://www.example.com/shows/my-personal-show-2.0-my-personal-show.htm

我们有数千个由Google编制的索引网址,需要通过.htaccess规则重新编写301重定向,以使其更具SEO性能而不会严重损害SERP。

提前致谢。

1 个答案:

答案 0 :(得分:0)

以SO为例,URL具有以下格式:

https://stackoverflow.com/questions/48077576/support-with-rewrite-url-in-patterns

要制作SEO友好网址,您可以将网址重写为:

https://www.example.com/shows/34565/my-personal-show-2.0

首先,您可以编写自己的路由器并将上述URL映射到实际的现有文件:

<强> .htacccess

RewriteRule ^shows/([0-9]+)/(.+)$ /router.php?id=$1&slug=$2 [QSA,L]

$1是对正则表达式部分([0-9]+)的反向引用,而$2是对正则表达式部分(.+)的反向引用。

对于 router.php ,您可以检查给定的idslug是否映射到现有的 htm文件

<强> router.php

if (isset($_GET['id']) && isset($_GET['slug'])) {
    $file_path = 'shows/' . str_replace('-', '_', $_GET['slug']) . '_' . $_GET['id'] . '.htm';
    if (file_exists($file_path)) {
        readfile($file_path);
    }
    else {
        header("HTTP/1.0 404 Not Found");
    }
    exit;
}

最后一件事是你应该将SEO不友好的URL永久重定向到SEO友好的URL。

<强>的.htaccess

RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_URI} ^/shows/(.+)\_([0-9]+)\.htm$
RewriteRule ^ /redirect.php?id=%2&slug=%1 [QSA,L]

<强> redirect.php

if (isset($_GET['id']) && isset($_GET['slug'])) {
    $redirectURL = '/shows/' . intval($_GET['id']) . '/' . str_replace('_', '-', $_GET['slug']);
    header('location: ' . $redirectURL, true, 301);
    exit;
}
相关问题