How to redirect to dynamic content with .htaccess

2019-03-06 11:10发布

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?

1条回答
我想做一个坏孩纸
2楼-- · 2019-03-06 12:07

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();
}
查看更多
登录 后发表回答