如何重定向到动态内容的.htaccess [英] How to redirect to dynamic content with .htaccess

查看:197
本文介绍了如何重定向到动态内容的.htaccess的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我知道如何编写搜索引擎友好的链接,我有这样的问题:如果我要使用的条目标题中的网址,然后链接打算,如果我更新的标题被打破。

现在我看到这个网站解决它以这种方式: http://stackoverflow.com/questions/123456/any-title-name

他们把ID在URL中,并在另一个地方是无关紧要的,因为如果任何用户更改标题,服务器将重定向到原标题标题。例如:

  • 如果用户键入: http://stackoverflow.com/questions/123456/i-changed-that-name-lol
  • 在服务器重定向到: http://stackoverflow.com/questions/123456/any-title-name

现在的问题是,你不能只使用的的.htaccess 的定期EX pressions,因为你必须要连接到数据库,以获得原题指定此手动。如何重定向做?

解决方案

您是对的,这是不可能通过的.htaccess做。还有一种方法,使通过Apache数据库连接,但我不认为这是可能的匹配,对在url当前标题。这意味着,它是最有可能的查询数据库的脚本,并发送一个重定向头回客户端。

在PHP中,你可以使用 头(.. 。)功能。随着Apache和PHP,你将获得code,它是这样的:

 < PHP
$匹配=阵列();
preg_match(/ ^ \ /问题/([0-9] +)\ /([^ \ /] +)$ /,$ _ SERVER ['REQUEST_URI'],$匹配);

$ DB =新的数据库();
$ seo_title = $ DB-> getTitleById($匹配[1]);
如果($ seo_title!= $火柴[2]){
  标题(位置:/问题/ {$匹配[1]} / {$ seo_title},TRUE,301);
  出口();
} 其他 {
  display_the_page();
}
 

Now that I know how to write SEO friendly links, I have this problem: If I'm going to use the entry title in the URL, then the links are going to be broken if I update that title.

Now I see that this site solved it in this way: http://stackoverflow.com/questions/123456/any-title-name

They put the ID in the URL, and the title in another place which is irrelevant because if any user changes that title, the server will redirect it to the original title. For example:

  • If the User types: http://stackoverflow.com/questions/123456/i-changed-that-name-lol
  • The server redirects to: http://stackoverflow.com/questions/123456/any-title-name

The problem is that you can't specify this manually using just .htaccess regular expressions, because you have to connect to the database in order to get the original title. How this redirection is done?

解决方案

You are right that this is impossible to do via .htaccess. There is a way to make a database connection via Apache, but I don't think it is possible to match that against the current title in the url. This means that it is most likely the script that queries the database, and sends a redirect header back to the client.

In php you can use the header(...) function. With Apache and php you would get code that looks like this:

<?php
$matches = Array();
preg_match("/^\/questions/([0-9]+)\/([^\/]+)$/", $_SERVER['REQUEST_URI'], $matches);

$db = new Database();
$seo_title = $db->getTitleById( $matches[1] );
if( $seo_title != $matches[2] ) {
  header( "Location: /questions/{$matches[1]}/{$seo_title}", TRUE, 301 );
  exit();
} else {
  display_the_page();
}

这篇关于如何重定向到动态内容的.htaccess的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆