how to block direct access to multiple thank you pages?

I have solved the issue by myself. I am posting the solution here in case if someone gets the same problem.

function wpse15677455_redirect() {
    $ref = wp_get_referer();
    if (is_page(1911) && $ref !== "https://www.example.com/contact"){
       wp_redirect( get_home_url() );
    }
    else if(is_page(1269) && $ref !== "https://www.example.com/contact-form-2"){
        wp_redirect( get_home_url() );
    }
    else if(is_page(1825) && $ref !== "https://www.example.com/contact-form-3"){
        wp_redirect( get_home_url() );
    }
    else if(is_page(1623) && $ref !== "https://www.example.com/contact-form-4"){
        wp_redirect( get_home_url() ); exit();
 };

tech