【问题标题】:Mod Rewrite automatically update URLMod Rewrite 自动更新 URL
【发布时间】:2014-12-31 04:49:47
【问题描述】:

我有一个网站,其中有一个带有 mod rewrite 的 .htaccess 文件,所以我的 URL 看起来更好看,对 SEO 更友好。

RewriteEngine on

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

ErrorDocument 404 /index.php?error=404

RewriteRule ^(admin)($|/) - [L]
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_]+)\.php$ index.php?country=$1
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_A-Яа-я-]+)/([a-zA-Z0-9_-]+)\.php$ index.php?country=$1&id=$3
RewriteRule ^([a-zA-Z0-9_-]+)/(.*)/(.*)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)\.php$ index.php?country=$1&subid=$5&id=$4
RewriteRule ^.+?---(.+)$ images/$1 [L,NE]
Rewriterule ^sitemap.xml$ sitemap.php [L]

正如您在上面的规则中看到的,有“通配符”意味着在一些正斜杠之间,任何事情都会发生。我使用它的方式是用于语言选择和命名页面标题,以 id 变量结尾以控制要显示数据库中表中的哪一行。示例:

http://www.domain.com/en/heaters/hot-heater/26/60.php

以上网址包含域/语言/通配符/通配符/id变量/id变量

现在的问题是,当页面上的链接按标题更新时(假设 hot-heater 将名称更改为 hot-red-heater),Google 索引的 URL 不一样,两个 URL 仍然有效.

我想知道如何使用 mod rewrite 自动将通配符更新为正确的标题。就像 Stackoverflow 上的这里一样,URL 在 URL 中有这个问题的标题 - 如果我在 URL 中更改它,URL 会自动将其更改回原始标题。这是怎么做到的?

非常感谢。

【问题讨论】:

    标签: regex apache .htaccess mod-rewrite redirect


    【解决方案1】:

    如果您需要像 Stackoverflow URL 一样的行为,那么您还需要一些服务器端支持(例如 PHP)。考虑以下代码 sn-p:

    .htaccess:

    RewriteEngine On
    RewriteRule ^([^/]+)/([^/]+)/?$ /index.php?id=$1&title=$2 [L,QSA]
    

    index.php:

    <?php
       $id    = $_GET['id'];
       $title = $_GET['title'];
    
       $dbTitle = // get title by doing a database query using $id
       // ...
    
       if ($title != $dbTitle) {
          // redirect with 301 to correct /<id>/<title> page
          header ('HTTP/1.1 301 Moved Permanently');
          header('Location: /' . $id . '/' . $dbTitle);
          exit;
       }
       // rest of your script
    ?>
    

    这将支持类似 SO 的 URL,即/id/some-title

    【讨论】:

    • 感谢@anabhava - 这实际上很有意义,我可以看到如何实现它并将其用作编码时的标准。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    相关资源
    最近更新 更多