Drupal – Allow access to a page only from a specific domain

Here I am explaining a requirement where website owners want to provide access  for a  page from particular website. If user try to access page from any where other than from a particular domain will be redirected to home page without showing landing page.

Suppose you are  running a website say www. x.com and you have a partner with a website www.y.com.  Suppose you want to provide a service to your partner using web page in Drupal and this page is only accessible for users who are coming from www.y.com, you partner site.

Before starting  ensure below PHP filter module is installed in you Drupal 8 instance.

https://www.drupal.org/project/php

Now we are creating  a basic page with title and  body as its  fields. Say created  page url is www.x.com/test

Now we are going to give this link in www.y.com and we need to restrict access only  from www.y.com

First we are going to create function in our custom module. Say function name as domain_restrict().

Create function in your module-name.module

function  domain_restrict(){
$Referer_domain = $_SERVER['HTTP_REFERER'];
$source = 'http://www.y.com';
}

In above function we are declaring two variables. We are keeping  our partner domain name as source and assign to source variable.

$_SERVER   variable array will contain all request parameter values. So we will get domain name from where request is coming using  $_SERVER[‘HTTP_REFERER’];

Assign this domain to $Referer_domain variable.

Now we need to check  $Referer_domain  url have $source domain. So we will use strops() function and check for presence of www.y.com.


function  domain_restrict(){
$Referer_domain = $_SERVER['HTTP_REFERER'];
$source = 'http://www.y.com';
if((strpos($RefererX, $source) === 0)){
return;
}
}

Function strpos(($RefererX, $source)  returns zero if referrer url present in $source. So if it is present , just use return. Else we need to redirect to       home page  without showing page www.x.com/test  . in order to redirect to home we need to add below code snippet in else part.

$url = \Drupal\Core\Url::fromRoute('<front>')->toString();
$response = new RedirectResponse($url);
$response->send();

So complete function will look like below.

function  domain_restrict(){
$Referer_domain = $_SERVER['HTTP_REFERER'];
$source = 'http://www.y.com';
if((strpos($RefererX, $source) === 0)){
return;
}else{
$url = \Drupal\Core\Url::fromRoute('<front>')->toString();
$response = new RedirectResponse($url);
$response->send();
}
}




Get Free E-book
Get a free Ebook on Drupal 8 -theme tutorial
I agree to have my personal information transfered to MailChimp ( more information )
if you like this article Buy me a Coffee this will be an ispiration for me to write articles like this.

You may also like...