Blog / WordPress/ How to Safely Convert External Links to Internal Redirects in WordPress Using Custom Fields

How to Safely Convert External Links to Internal Redirects in WordPress Using Custom Fields

WordPress 自定义字段外链转内链跳转的实现方法与安全指南

Implementation Principle and Steps

This method creates a redirect page that processes external links, making them appear as internal links on your WordPress front-end. This is commonly used to hide the actual external URL or to track link clicks.

Step 1: Create the Redirect Page File

In your WordPress root directory, create a new folder (e.g., redirect) and inside it, create an index.php file.

File content:

<?php
// Security check: verify request origin and parameters
if (empty($_GET['url']) || !isset($_SERVER['HTTP_REFERER']) || strpos($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']) === false) {
    wp_die('Invalid access.'); // Use this if in WordPress context
    // For non-WordPress: die('Invalid access.');
}

// Get and decode the Base64-encoded URL parameter
$encoded_url = sanitize_text_field($_GET['url']);
$target_url = base64_decode($encoded_url);

// Secondary validation: is the decoded string a valid HTTP/HTTPS URL?
if (filter_var($target_url, FILTER_VALIDATE_URL) === false) {
    wp_die('Invalid link.');
}
// Perform redirect (with brief delay for potential tracking code)
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <title>Redirecting...</title>
    <meta http-equiv='refresh' content='0.5;url=<?php echo esc_url($target_url); ?>'>
</head>
<body>
    <p>Redirecting to the target page, please wait...</p>
</body>
</html>

Step 2: Generate the Redirect Link in Custom Fields

In your WordPress post/page editor, use a custom field to store the external link. In your template file (e.g., single.php), use the following code to read and generate a secure redirect link.

Assuming your custom field name is external_link:

<?php
$external_url = get_post_meta(get_the_ID(), 'external_link', true);
if (!empty($external_url)) {
    // Encode the original external URL in Base64
    $encoded_url = base64_encode($external_url);
    // Build the full URL to the redirect page
    $redirect_link = site_url('/redirect/') . '?url=' . urlencode($encoded_url);
    // Output the link HTML
    echo '<a href="' . esc_url($redirect_link) . '" rel="external nofollow noopener" target="_blank">Visit External Resource</a>';
}
?>

Critical Security Notes and Best Practices

Basic redirect code without filtering and validation creates a serious open redirect vulnerability, allowing attackers to craft malicious links to phishing sites.

  • Always Verify Origin: Check HTTP_REFERER to ensure the request comes from your own site.
  • Always Validate the URL: Use filter_var() to confirm the decoded string is a valid URL.
  • Always Escape Output: Use WordPress functions like esc_url() to prevent XSS attacks.
  • Consider a More Robust Solution: For production, use a dedicated plugin (e.g., Pretty Links) or a well-coded redirect controller with click logging.

Extending the Solution

You can add functionality to the redirect index.php page:

  1. Click Tracking: Log click data (link ID, timestamp, IP) to the database before redirecting.
  2. User Notification Page: Design a friendly interstitial page informing users they are leaving your site, showing the target domain.
  3. Dynamic NoFollow Control: Programmatically add or omit the rel="nofollow" attribute based on link type.

Using this method, you can safely convert external links in WordPress into controlled internal redirects.

Post a Comment

Your email will not be published. Required fields are marked with *.