URL Change – Check if Post Exists Before 404

function checkArtist() {
    $page = get_page_by_path($_SERVER['REQUEST_URI']."https://wordpress.stackexchange.com/",OBJECT,'artist');

    if($page){
        header("HTTP/1.1 301 Moved Permanently"); 
        header("Location: /artist".$_SERVER['REQUEST_URI']);
    }
}
add_action( 'wp', 'checkArtist' );

I add a custom hook using wp which as the article says:

This hook is one effective place to perform any high-level filtering
or validation, following queries, but before WordPress does any
routing, processing, or handling.

The function then uses get_page_by_path to retrieve a page given its path. The path is took from the URL using PHP $_SERVER['REQUEST_URI']. If it exists for that particular post type then I do a 301 redirect.