2014-11-04 60 views
2

我有一个网站,我有一个.htaccess文件与mod重写,所以我的网址有点更好看,更多的搜索引擎优化友好。Mod Rewrite自动更新URL

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

以上URL包含域/的langugage /通配符/通配符/ id变量/ id变量

现在的问题是,当页面上的链接得到由标题更新(假设热水器的名称改为热红加热器),谷歌索引的URL并不相同,并且这两个URL仍然有效。

我想知道如何使用mod重写来自动更新通配符到正确的标题。就像这里在Stackoverflow上一样,URL在URL中有这个问题的标题 - 如果我在URL中改变了这个,URL会自动将它改回原来的标题。这是如何完成的?

非常感谢提前。

回答

1

如果您需要具有像Stackoverflow URLs一样的行为,那么您还需要一些服务器端支持(例如PHP)。考虑下面的代码片段:

的.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 
?> 

这将支持URL像这样即/id/some-title

+1

感谢@anabhava - 这实际上很有意义,我可以看到我如何实现这个并将其用作一个我编码时的标准。再次感谢! – MazeyMazey 2014-11-07 20:38:36

+0

不客气,很高兴帮助。 – anubhava 2014-11-07 20:42:57