0

So I've moved my website from site.com to sub.site.com. I have also moved the booking system.

Is it possible for me to have PHP code on index.php on site.com to check if the user wanted site.com/unbook.php to automatically redirect them to sub.site.com/unbook.php

The optimal thing would be some kind of "redirect everything if there is anything in the url other than site.com"

Something like

$urlafter = explode("site.com", $url);
if (strlen ($urlafter[1]) > 0 ) {
    header("Location: sub.site.com".$urlafter[1]);
    exit();
}

Or would it be better using something like $_SERVER[REQUEST_URI] or even .htaccess

-- EDIT --

Non duplicate because they only show .htaccess answers, I'd prefer PHP

Richard Muthwill
  • 320
  • 2
  • 16
  • If you are an Apache user, use [htaccess](https://help.dreamhost.com/hc/en-us/articles/217738987-What-can-I-do-with-an-htaccess-file-), dont forget the correct `STATUS CODE` – kip Jul 22 '18 at 01:11
  • 1
    Possible duplicate of [Redirect all urls exactly, just change domain name](https://stackoverflow.com/questions/19816284/redirect-all-urls-exactly-just-change-domain-name) – Jacob Jul 22 '18 at 01:13
  • Thanks Jacob! I did try searching but couldn't find anything to help. Do you have a PHP version too? – Richard Muthwill Jul 22 '18 at 01:14

1 Answers1

0

Using Htacces is better for the scenerio. In the .htaccess file at the site.com you can set the following rule to redirect:

Redirect 301 / http://sub.site.com/

301 is for permanent redirect.
If the redirect is temporary, you can use 302 instead.

In Php you can use the following code to replace the domain:

$uri = $_SERVER['REQUEST_URI'];
$old_domain = 'yoursite.com';
$new_domain = 'sub.yoursite.com';

$old_domain_pos = strpos($url, $old_domain);

$redirect_url = substr($url, 0, $old_domain_pos).$new_domain.substr($url, ($old_domain_pos+strlen($old_domain)));

The above code replaces the domain only once, leaving everything else as it is. If your url is like the following, where the domain may repeat in the querystring, which themselves need to be replaced.

http://www.yoursite.com/get/?assset=www.yoursite.com/imgs/pic01.png

then you can consider string_replace method.

$redirect_url = str_replace($old_domain, $new_domain, $url);
Tanvir Ahmed
  • 483
  • 3
  • 10