Search code examples
phphttp-redirectpantheon

Cannot redirect correctly with PHP


I have a blog in a website that I want to redirect.

For example this URL https://example.com/blog/june-2021/name-of-blog-post should redirect to https://example2.com/blog/june-2021/name-of-blog-post

There are hundreds of blog posts so I can't use an array to redirect them one by one.

I'm using Pantheon as the host. I added the script to settings.php.

Currently everything from example.com goes to example2.com, so it's not working correctly.

Here's my script:

$url = $_SERVER['REQUEST_URI'];

$uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri_segments = explode('/', $uri_path);
$blog = $uri_segments[0];
$post_date = $uri_segments[1];
$post_name = $uri_segments[2];

if ((stripos($url, "/blog/") === 0) && (php_sapi_name() != "cli")) {
  header('HTTP/1.0 301 Moved Permanently'); header("Location: https://example2.com".$blog.$post_date.$post_name);
  if (extension_loaded('newrelic')) {
    newrelic_name_transaction("redirect");
  }
exit(); }

Thanks in advance!


Solution

  • You can check for /blog/ by checking that it is found !== false anywhere in $_SERVER['REQUEST_URI']:

    if ((stripos($url, "/blog/") !== false) && (php_sapi_name() != "cli")) {
    

    Or check to see if it is found at the first 0 position of $_SERVER['REQUEST_URI']:

    if ((stripos($url, "/blog/") === 0) && (php_sapi_name() != "cli")) {
    

    Notes:

    1. stripos only takes three arguments and you only need the first two.
    2. Location header should consist of a single absolute URI like https://example2.com/blog/june-2021/name-of-blog-post, so you might look at the other $_SERVER variables to construct one.