This is for a project. I need to redirect certain incoming URL requests to files hosted on the same webserver. I cannot use .htaccess and I cannot rely on any plugins.
I managed to do this with a plugin but I am having a hard time extracting the necessary code in order to write my own plugin which does what I need to do hardcoded.
- WordPress Multisite
All software up to date
"Redirection" WordPress Plugin (sucessfully)
- writing custom WP functions to do this (semi-successfully)
I found some code in the Pantheon documentation:
$blog_id = get_current_blog_id();
// You can easily put a list of many 301 url redirects in this format
// Trailing slashes matters here so /old-url1 is different from /old-url1/
$redirect_targets = array(
'/test/test.xml' => '/files/' . $blog_id . '/test.xml',
'/regex/wildcard.xml(.*)' => '/files/' . $blog_id . '/regex.xml',
);
if ( (isset($redirect_targets[ $_SERVER['REQUEST_URI'] ] ) ) && (php_sapi_name() != "cli") ) {
echo 'https://'. $_SERVER['HTTP_HOST'] . $redirect_targets[ $_SERVER['REQUEST_URI'] ];
header('HTTP/1.0 301 Moved Permanently');
header('Location: https://'. $_SERVER['HTTP_HOST'] . $redirect_targets[ $_SERVER['REQUEST_URI'] ]);
if (extension_loaded('newrelic')) {
newrelic_name_transaction("redirect");
}
exit();
}
https://example.com/test/test.xml sucessfully
redirects to
/files/5/text.xml
However, some incoming requests contain a query string, e.g.
https://example.com/regex/wildcard.xml?somequerystring
obviously, the redirect from
https://example.com/regex/wildcard.xml
to
/files/5/regex.xml
works fine.
However, as soon as there is a query string involved, the redirect does not work. Given that I need to do this with PHP, how can I achieve a wildcard redirect from either /regex/* or /regex/wildcard.xml* to /files/5/regex.xml?
Any help would be greatly appeciated.
Thanks, Daniel