wp_safe_redirect()WP 2.3.0

Performs a safe redirect, using wp_redirect(). Before redirections check whether the host is in whitelist (in list of allowed hosts).

Before redirecting to the specified host (url), the function checks it. Redirection will occur only if the host is present in the list of allowed hosts.

If the host is not allowed, then the redirect defaults to http://site.com/wp-admin instead. This prevents malicious redirects which redirect to another host. With this approach, you can protect users from getting to an unsafe site.

The list of allowed hosts can be extended by plugins, see hook allowed_redirect_hosts().

This is a pluggable function, and it can be replaced by a plugin. It means that this function is defined (works) only after all plugins are loaded (included), but before this moment this function has not defined. Therefore, you cannot call this and all functions depended on this function directly from a plugin code. They need to be called on plugins_loaded hook or later, for example on init hook.

Function replacement (override) — in a plugin you can create a function with the same name, then it replace this function.

Hooks from the function

Return

true|false. False if the redirect was cancelled, true otherwise.

Usage

wp_safe_redirect( $location, $status, $x_redirect_by );
$location(string) (required)
The path or URL to redirect to.
$status(int)
HTTP response status code to use. (Moved Temporarily).
Default: '302'
$x_redirect_by(string)
The application doing the redirect.
Default: 'WordPress'

Examples

0

#1 Secure redirection

Let's imagine that we pass a redirect link to the wp_safe_redirect() function and it changes depending on the user's actions, i.e. it can always be different. And we need to make sure that the redirection will occur only if site internal URL was passed. This code will help us:

if( isset( $_POST['location'] ) ){
	wp_safe_redirect( $_POST['location'] );
	exit;
}

Changelog

Since 2.3.0 Introduced.
Since 5.1.0 The return value from wp_redirect() is now passed on, and the $x_redirect_by parameter was added.

wp_safe_redirect() code WP 6.1.1

function wp_safe_redirect( $location, $status = 302, $x_redirect_by = 'WordPress' ) {

	// Need to look at the URL the way it will end up in wp_redirect().
	$location = wp_sanitize_redirect( $location );

	/**
	 * Filters the redirect fallback URL for when the provided redirect is not safe (local).
	 *
	 * @since 4.3.0
	 *
	 * @param string $fallback_url The fallback URL to use by default.
	 * @param int    $status       The HTTP response status code to use.
	 */
	$location = wp_validate_redirect( $location, apply_filters( 'wp_safe_redirect_fallback', admin_url(), $status ) );

	return wp_redirect( $location, $status, $x_redirect_by );
}