I was asked to change Mediawiki’s #REDIRECT handling from transparent redirects to SEO friendly 301 redirects. I tried to create some extensions but none of the hooks seemed to provide a way to change the redirect functionality the way I needed to.
Turns out I only needed to edit Article.php and Wiki.php with very minor 1 line changes. Haven’t seen this posted anywhere else so enjoy.
#Article.php - Changed line 32 to return $rt->getFullUrl();
function followRedirect() {
$text = $this->getContent();
$rt = Title::newFromRedirect( $text );
# process if title object is valid and not special:userlogout
if( $rt ) {
if( $rt->getInterwiki() != '' ) {
if( $rt->isLocal() ) {
// Offsite wikis need an HTTP redirect.
//
// This can be hard to reverse and may produce loops,
// so they may be disabled in the site configuration.
$source = $this->mTitle->getFullURL( 'redirect=no' );
return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
}
} else {
if( $rt->getNamespace() == NS_SPECIAL ) {
// Gotta handle redirects to special pages differently:
// Fill the HTTP response "Location" header and ignore
// the rest of the page we're on.
//
// This can be hard to reverse, so they may be disabled.
if( $rt->isSpecial( 'Userlogout' ) ) {
// rolleyes
} else {
return $rt->getFullURL();
}
}
return $rt->getFullUrl();
}
}
// No or invalid redirect
return false;
}
#Wiki.php - Changed line 11 to $output->redirect( $article, "301" );
function initialize ( &$title, &$output, &$user, $request) {
wfProfileIn( 'MediaWiki::initialize' );
$this->preliminaryChecks ( $title, $output, $request ) ;
$article = NULL;
if ( !$this->initializeSpecialCases( $title, $output, $request ) ) {
$article = $this->initializeArticle( $title, $request );
if( is_object( $article ) ) {
$this->performAction( $output, $article, $title, $user, $request );
} elseif( is_string( $article ) ) {
$output->redirect( $article, "301" );
} else {
throw new MWException( "Shouldn't happen: MediaWiki::initializeArticle() returned neither an object nor a URL" );
}
}
wfProfileOut( 'MediaWiki::initialize' );
return $article;
}