How to set redirect URL programmatically in magento 2?

In Magento 2, You can set redirect to any link URL by the Magento\Framework\Controller\Result\RedirectFactory Class.

    • Using setUrl($url) -> You need to pass the link as a parameter for redirect
    • Using setPath($path) -> You need to pass path(action URL) as parameter
public function __construct(
    \Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory
) {
    $this->resultRedirectFactory = $resultRedirectFactory;
}

1. Using a direct path, you need to pass the action URL in a setPath() method.

    • Redirect to the cart page,  Pass the action path as checkout/cart
    • Redirect to the contact page, the parameter is contact only
    • To Redirect to a login page, a parameter is customer/account/login
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('checkout/cart');
return $resultRedirect;

2. Pass Query string, Add Second Argument as a Query string array to use custom query string in URL.

$argument = ['id' => $getId, '_current' => true];
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('checkout/cart', $argument);
return $resultRedirect;

3. Full URL redirect with Magento,

$url = 'https://magento.test/checkout/cart';

$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setUrl($url);
return $resultRedirect;

You need to pass the full URL for a redirect to a specific link in Magento 2 in the setUrl method.

You can check to Get Referer URL in Magento for your knowledge.