Menu

How to Create Safe External Redirects in WordPress
🖼️

How to Create Safe External Redirects in WordPress

DEV Community·anti Gym Club·6 months ago
#UaurtusJ
#security#wordpress#php#redirect#return
Reading 0:00
15s threshold

You want to redirect a WordPress post to an external URL. Maybe it's an affiliate link, a resource that moved, or a curated link collection.

The naive approach using wp_redirect() with any URL opens security holes. Here's how to do it safely.

The Problem with wp_redirect()

// DON'T DO THIS wp_redirect ( $_GET [ 'url' ] ); exit ;

Enter fullscreen mode

Exit fullscreen mode

This is an open redirect vulnerability. Attackers can craft URLs like:

yoursite.com/post?url=https://malicious-site.com

Enter fullscreen mode

Exit fullscreen mode

And use your domain's reputation to phish users.

Safe External Redirects

WordPress provides wp_safe_redirect() , but it only allows redirects to whitelisted hosts. For external URLs, we need validation:

/** * Safely redirect to an external URL * * @param string $url Destination URL * @param int $status_code HTTP status code (301, 302, 307) */ function safe_external_redirect ( $url , $status_code = 301 ) { // Validate URL format if ( !…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.