Essential Redirects In Php Production

Redirecting in PHP: Usage and best practices.

This article aims to detail the redirects needed when writing PHP in production environments, their necessity and how to implement them safely.


What is Redirecting

Redirecting involves moving or forwarding a request from a user or a search engine directed to a URL address to another address. Redirects are essential for the proper operation of a website and can be implemented by writing pieces of PHP code or using the .htaccess file (in Apache hosting) or on the client side with the meta tag or JavaScript. However, it's important to note that client-side implementations can be slow, bypassable, and often go unrecognized by search engines. Therefore, it is imperative to implement redirects through the server.

The most straightforward way to perform redirection in PHP is by using the header function, like this:

header('Location: ./mylocation');

The header function is useful in numerous cases, including login or sign-up validation, page protection, and many other scenarios.

As your website goes live and becomes accessible to the public, the need for redirection increases.

Some of these types of redirects can also be implemented in other server-side languages, but the implementation may differ. A forthcoming article will delve into this topic for Node.js.

SSL Redirects (Moving HTTP Requests to HTTPS)

While HTTP addresses are suitable for local use with your localhost or local IP address, they are vulnerable and unsafe for production. In such cases, it is essential to transfer requests to HTTPS, provided you have an active SSL certificate on your server. This ensures that every request to http://example.com is redirected to https://example.com. You can achieve this in your code using the following sample code:

<?php // Is request in HTTPS
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on') {
    // Redirect to HTTPS
     $redirect_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; 
    header("Location: $redirect_url");
    exit; 
}

WWW Redirects

Websites need to be correctly configured with their subdomains. Sometimes, we also want https://sub.example.com to redirect to https://example.com. In some cases, sites need to redirect to their "www" version, such as https://google.com redirecting to https://www.google.com.

<?php

function goToNonWWW() { 
    $redirect_url = "https://" . substr($_SERVER['HTTP_HOST'], 4) . $_SERVER['REQUEST_URI']; 
    header("Location: $redirect_url");
    exit; 
} 

function goToWWW() {
    $redirect_url = "https://www" . substr($_SERVER['HTTP_HOST'], 4) . $_SERVER['REQUEST_URI']; 
    header("Location: $redirect_url");
    exit; 
}

// Check if the domain starts with "www"
if (substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.') { 
    // goToNonWWW(); 
} else { 
    goToWWW(); 
}

In other cases, "www" versions should redirect to the non-"www" version. To enable this, comment out goToWWW() instead of goToNonWWW();.

Domain Forwarding

Also known as URL forwarding, domain forwarding becomes necessary when the address for a website changes, either permanently or temporarily. Redirects are essential to prevent broken links and SEO errors. In other cases, site owners may wish to have multiple domain names point to the same site.

Page Forwarding

Page forwarding serves several crucial purposes. Some of these cases are listed below:

  1. Page Access Protection: There may be a need to restrict access to a specific page for certain users. For example, requests to https://example.com/admin or https://example.com/user/4567123/settings by other site users should be redirected elsewhere.

  2. Obsolete Page Content: When the content on a page is no longer valid, page forwarding can guide visitors to relevant, up-to-date information.

  3. Deleted or Broken Pages: If pages have been removed or are no longer functioning, proper forwarding can guide users to alternative content or a relevant error page.

  4. Duplicate Pages: To prevent confusion and improve SEO, forwarding can be used to consolidate duplicate pages under a single URL.

  5. Page Maintenance: During maintenance or updates, forwarding can be employed to direct users to an informative maintenance page, ensuring a better user experience.

Redirecting with the .htaccess file

The .htaccess file is a configuration file used to modify the behavior of the Apache HTTP Server for a specific directory or subdirectory.

It is crucial to thoroughly test the .htaccess file to ensure it functions correctly. The .htaccess file can significantly impact a website's performance and behavior, so it should be used with caution. Most Apache hosting services provide a prepared .htaccess file in your directory. It's important to handle the existing configuration with care.

Here is an example of common redirects implemented in a single .htaccess file:

# Redirect all requests to HTTPS
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Redirect all requests for non-www to www
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Redirect all requests for old-page to new-page
RewriteRule ^old-page$ https://www.example.com/new-page [L,R=301]

3xx redirects

3xx redirects are HTTP status codes that indicate a request would be redirected to another address. Using the appropriate status code is crucial for improving Search Engine Optimization (SEO) and site performance. Here is a list of 3xx redirects:

300 Multiple Choice: This code indicates that the client has multiple options to choose from. The response includes a "Location" header field that the client can use.

301 Moved Permanently: This status code signifies a permanent relocation of the requested resource to a new URL. The client should update any bookmarks and links to point to the new URL.

302 Found (Previously "Moved Temporarily"): This status code indicates that the requested resource has been temporarily moved to a new URL. It was previously labelled as "Moved Temporarily." For subsequent requests, the client should continue using the original URL.

303 See Other: This status code signifies that the server has forwarded the client to another resource, which must be retrieved using a GET request.

304 Not Modified: This status code indicates that the requested resource is still valid in the client's cache and does not require retrieval from the server.

305 Use Proxy: This status code suggests that the client must use a proxy to access the requested resource.

307 Temporary Redirect: Similar to 302, this status code indicates a redirect, but the client should keep using the same URL for future queries.

Safely Redirecting

Performance Impact

Redirects can have a significant impact on server performance and page load times. This can be detrimental from a user experience perspective and can add stress to the server. While single redirects are generally acceptable, it's crucial to avoid chains of redirects (multiple redirects leading to more redirects) whenever possible.

Avoid Linking to Pages with Redirects

Including links to pages that are subject to redirection should be avoided in new content. Doing so helps mitigate the performance impact and ensures a smoother user experience.

Avoid "Header Already Sent" Errors

In PHP, the header function must be used before any output is sent to the browser. Consider this example:

<?php
echo "<title>";
header("Location: ");

This code would trigger the common "header already sent" error. To prevent this, you can simply place the header function before any output or utilize output buffering. For more information on output buffering, you can read about it here.

Conclusion

Redirects are a fundamental tool for any PHP developer working on the web. Whether you are using them to reroute traffic from one domain to another or to direct users to a new URL after form submission, redirects play a vital role in optimizing PHP applications for user experience and SEO.

In addition to the points mentioned, it's important to keep in mind that redirecting should be used judiciously. Excessive or improper use of redirects can lead to a confusing user experience and negatively impact your website's SEO. Always test your redirects thoroughly to ensure they work as intended and monitor their performance over time.

Additionally, consider implementing best practices, such as using HTTP status codes appropriately and providing clear and informative messages to users when redirection is necessary. By doing so, you can harness the power of redirects to enhance your website's functionality while maintaining a smooth and efficient user journey.