Using nginx rewrite with many individual URLs

2019-07-31 14:42发布

问题:

I need to rewrite a large number of URLs (about 250) on nginx.

from: http://xyzwiki.de/wiki/index.php?title=Article1

to: http://wiki.zyx.de/wiki/AlternativeNameForArcticle1

As obviously the source does use classic url and also other names for the individual articles I have a table with all the sources and destinations.

I have tried to work with the basic redirect examples however I did not get it to work. I think the reason for this might be that the source URLs use URL parameters - but I did not find a solution for this.

So I'd need a mapping where I tell nginx a bunch of source URLs and their respective rewrite target.

回答1:

Personally, I'll handle this in php using the auto_prepend_file facility.

With this, the code block below will run for every php call if saved somewhere on the server and the auto_prepend_file set to load it.

if ($_SERVER['SCRIPT_NAME'] == '/index.php') {
    // only proceed if this is the root index.php file 
    $title = $_GET['title'];
    $urlMap = array (
            'article1' => 'alternative1',
            'article2' => 'alternative2',
            'article3' => 'alternative3',
            ...
            'article250' => 'alternative250'
    );

    if (array_key_exists($title, $urlMap)) {
        // redirect to alternative url
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: http://wiki.zyx.de/wiki/" . $urlMap[$title]);
        exit;
    } else {
        // unset vars and continue otherwise
        unset($title);
        unset($urlMap); 
    }
}