Search code examples
javascriptphphtmlwordpress.htaccess

how to Restrict access to some urls of wordpress website from single referrer domain


hello my question is what is the best approach to Restrict access to some urls of wordpress website to single referrer domain. as far as I am familar with javascript I found a way for that. but I think javascript code is not good, because the source code of the page does not change. I wrote this code:

function getCookie(name) {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(';').shift();
    }
    document.body.style.display="none";
    var url = document.referrer;
    var domainname;
    var referal_code = getCookie("protect_faq_pages");
    console.log(url);
    if(url){
        var anchor = document.createElement("a");
        anchor.href = url;
        domainname = anchor.host;
        console.log(domainname);
        if(domainname == "softwareservicetech.com"){
             var cookieString = "protect_faq_pages=cWs@fgf$a1fD#FsC-)";
             document.cookie = cookieString;
        }
    }else if(!(referal_code == "cWs@fgf$a1fD#FsC-)")){
            document.getElementById("page").innerHTML="<p>Sorry you do not have permission to view the content</p>"
        }
    console.log(referal_code);
    document.body.style.display="block";

this site can be accessed itself: https://health-unity.com/ you can find out the page below is restriced on the view : https://health-unity.com/help-centre/videos/ and also these pages too: https://health-unity.com/help-centre/videos/video-number-2/ https://health-unity.com/help-centre/videos/video-number-1/ but when click on the link on below site (link to health-unity-videos): https://softwareservicetech.com/testpage/ the archive page will be accessible after that. user can go to the pages below directly: https://health-unity.com/help-centre/videos/video-number-2/ https://health-unity.com/help-centre/videos/video-number-1/ these were restricted before and now can be accessed by a cookie that is set. but the problem is that page source still exist and did not changed by javascript code and user can view the page source. also I want that the cookie value should be hidden. because of these two problem I think javascript is not a good idea. please share with me if there is way with javascript, php, or editing functions.php or .htaccess file to achieve this. thank you for your response in advance


Solution

  • You can use $_SERVER['HTTP_REFERER'] in functions.php

    For example:

    <?php
    
    add_action('init','check_referrer');
    
    function check_referrer(){
    
        if (str_contains($_SERVER['HTTP_REFERER'], 'https://example-domain.com/')){
            // do something
        }else{
            // do something else
        }
    }
    ?>