Search Our Database

How to create page redirection using PHP on linux server.

Last updated on |
by

Introduction

This article is for web developers, server administrators, and website owners who need to set up page redirection using PHP. It addresses how to redirect users from one webpage to another, which is particularly useful if the original page no longer exists or content has been moved.

Follow the steps carefully to ensure the redirection functions properly and doesn’t conflict with existing index files. Always verify that the redirection is working as expected after implementation.

 

Prerequisites

  • A Linux-based server with PHP installed
  • SSH access to the server (with root privileges)
  • Basic knowledge of file editor via command line (vi or nano)

 

Steps

Step 1: Access to the server via SSH

  • Open a terminal on your local machine
  • You can use the following command to connect to the server
    ssh username@your-server-ip -p22
  • Replace the username with your actual username and your-server-ip  with your server’s IP address. The port number also need to specify incase, you have configured the port number for SSH access to the server.
    Important Note: If prompted with the private key, you will need to include the  private key in the command as well to connect to your server.

 

Step 2: Navigate to Domain DocumentRoot Directory.

  • Once you have successfully connected to the server, navigate to page you wish to create the redirection. In this example, we navigate to the web DocumentRoot.
    cd /var/www/html/
  • Use this command to create index.php
    vi index.php
    Important Note: If no index.php existed, this command will create a new file. If otherwise, you  can consider to make a backup before altering index.php
  • You can paste the command as following
    <?php
    // The new location to which users should be redirected
    header("Location: https://www.newdomain.com/new-page.php");
    exit();
    ?>
    
    Important Note: If there is index.html inside the directory, you will need to change it to other name such as index_backup.html. This is because the index.html  will overwrite any configuration in the path.
  • You can verify the redirection by browsing through the domain, and it should be redirected to the site you intended.

 

Conclusion

By following these steps, you can implement page redirection using PHP, which is essential when reorganizing your website’s content or structure. Proper redirection helps maintain a positive user experience by preventing visitors from landing on broken links or outdated pages.

Article posted on 22 March 2020.