Making WordPress.org

Changeset 10487


Ignore:
Timestamp:
12/04/2020 02:20:12 AM (5 years ago)
Author:
dd32
Message:

Redirects: Catch some malformed URL requests and redirect it to a better location.

Fixes #5528.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • sites/trunk/wordpress.org/public_html/wp-content/mu-plugins/pub/wporg-redirects.php

    r10386 r10487  
    9999
    100100/**
     101 * Redirect some invalid/malformed URL requests to their proper locations.
     102 */
     103add_action( 'template_redirect', function() {
     104    global $wp;
     105
     106    if ( ! is_404() ) {
     107        return;
     108    }
     109
     110    $name = false;
     111    foreach ( [ 'name', 'attachment', 'pagename' ] as $field ) {
     112        if ( isset( $wp->query_vars[ $field ] ) ) {
     113            // Get the raw unmodified query var from WP directly.
     114            $name = urldecode( $wp->query_vars[ $field ] );
     115        }
     116    }
     117    if ( ! $name ) {
     118        return;
     119    }
     120
     121    $new_path = $path = $_SERVER['REQUEST_URI'];
     122
     123    // Remove any common URL paths.
     124    $new_path = preg_replace( '!^/?(index|contact(-us)?)(\.(html?|php))?!i', '', $new_path );
     125
     126    // Remove any `<a>` attributes from the URL.
     127    $new_path = preg_replace( '!(target|rel|href)=?(.+)$!i', '', $new_path );
     128
     129    // Remove any trailing punctuation.
     130    $new_path = preg_replace( '!([ +\'"\W]|(?:%20))+$!', '', $new_path );
     131
     132    if ( $path === $new_path ) {
     133        return;
     134    }
     135
     136    // Determine URL, save a redirect and check the canonical too.
     137    $url = home_url( $new_path );
     138    if ( $canonical_url = redirect_canonical( $url, false ) ) {
     139        $url = $canonical_url;
     140    }
     141
     142    wp_safe_redirect( $url, 301, 'W.org Redirects Malformed URLs' );
     143    die();
     144
     145}, 20 ); // After canonical.
     146
     147/**
    101148 * Handle the domain-based redirects
    102149 *
Note: See TracChangeset for help on using the changeset viewer.