开发者

Can mod_rewrite do math?

开发者 https://www.devze.com 2023-01-03 16:06 出处:网络
I am planning to convert my website to a new CMS, but I 开发者_如何学Cwould like to use mod_rewrite to seamlessly redirect old links to their new locations.

I am planning to convert my website to a new CMS, but I 开发者_如何学Cwould like to use mod_rewrite to seamlessly redirect old links to their new locations.

The catch is that my new blog will not have the same article numbers as the old, because I'll import some older blog entries in their first. Thus, my mod_rewrite would need to take a URL like old.php?article=125, do the addition to figure out the new article number (say +200, for this example), and redirect to new.php?i=325.

Can mod_rewrite do the addition on its own, or am I going to need some kind of 'helper' script to do that?


Mod rewrite can do regular expressions. If you can define the value of your new articles to be the same id plus 1000 than you can do:

rewriteRule /article=(\d{1})$ /new.php?i=100$1
rewriteRule /article=(\d{2})$ /new.php?i=10$1
rewriteRule /article=(\d{3})$ /new.php?i=1$1


It can not do math. Maybe you want to use a rewrite map.


One option is to completely forget about old links in your .htaccess file. Instead, build a custom 404 Not Found error page and configure Apache to serve it on broken links. That page will be a PHP script and it'll test the $_SERVER['REQUEST_URI'] variable against simple expression:

<?php

if( substr($_SERVER['REQUEST_URI'], 0, 7)=='old.php' ){
    // Old link found!
}

?>

Inside the "old link found" condition, you can do further processing:

  1. Run a regular expression to find an article ID
  2. Do math on it and try to match it against a new ID
  3. Perform a permanent redirection with header()


I believe that's pushing the "voodo magic" that is mod_rewrite. I would either design a helper script to follow this up, or actually migrate at a database level the old entries.

The latter would give you much better stability and control over how the system it laid out. You would have new post id's for all the old entries and everything should fit seamlessly.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号