接著上一篇文章 《WordPress 網站終極防黑手冊,全方位保護網站安全 (一) 》小編繼續來談談 WordPress 系統的一些已知安全隱患。老鳥級別的 WordPress 站長一定知道不管在任何版本的 WordPress 程式上作者存檔頁面的固定連結都是不能修改的,而且一旦站長開啟偽靜態後,只要直接訪問

abc.com/?author=$id
(PS:id 為使用者的數字 id)

則 WordPress 會直接轉跳到

abc.com/author/使用者帳號/

這種形式的連結,這將直接暴露出網站使用者的登入帳號,存在著一定的安全隱患。 (PS:管理員的 ID 都是 1-5 這五個數字,直接一試管理員帳號就暴露了,然後密碼字典你懂的

。)

檢視 WordPress 原始檔發現作者存檔頁面連結是這樣獲取的:

/**
 * Retrieve the URL to the author page for the user with the ID provided.
 *
 * @since 2.1.0
 * @uses $wp_rewrite WP_Rewrite
 * @return string The URL to the author's page.
 */
function get_author_posts_url($author_id, $author_nicename = '') {
    global $wp_rewrite;
    $auth_ID = (int) $author_id;
    $link = $wp_rewrite->get_author_permastruct();

    if ( empty($link) ) {
        $file = home_url( '/' );
        $link = $file . '?author=' . $auth_ID;
    } else {
        if ( '' == $author_nicename ) {
            $user = get_userdata($author_id);
            if ( !empty($user->user_nicename) )
                $author_nicename = $user->user_nicename;
        }
        $link = str_replace('%author%', $author_nicename, $link);
        $link = home_url( user_trailingslashit( $link ) );
    }

    $link = apply_filters('author_link', $link, $author_id, $author_nicename);

    return $link;
}

那麼只要重寫下規則即可改變作者存檔頁面的連結,這裡以作者 ID 為例:(將以下程式碼加入到 functions.php 檔案)

add_filter( 'request', 'wxd_author_link_request' );
function wxd_author_link_request( $query_vars ) {
    if ( array_key_exists( 'author_name', $query_vars ) ) {
        global $wpdb;
        $author_id=$query_vars['author_name'];
        if ( $author_id ) {
            $query_vars['author'] = $author_id;
            unset( $query_vars['author_name'] );
        }
    }
    return $query_vars;
}
add_filter( 'author_link', 'wxd_author_link', 10, 2 );
function wxd_author_link( $link, $author_id) {
    global $wp_rewrite;
    $author_id = (int) $author_id;
    $link = $wp_rewrite->get_author_permastruct();

    if ( empty($link) ) {
        $file = home_url( '/' );
        $link = $file . '?author=' . $author_id;
    } else {
        $link = str_replace('%author%', $author_id, $link);
        $link = home_url( user_trailingslashit( $link ) );
    }

    return $link;
}

再次訪問

abc.com/?author=$id

則轉跳到

abc.com/author/$id

這樣一來就不會暴露網站使用者以及管理員賬號了。