How to redirect users to the last page viewed

Give this a try…

function save_url_before_login() {
  if(!is_user_logged_in()) {
    $_SESSION['referer_url'] = get_the_permalink();
}
add_action('wp', 'save_url_before_login');

and:

function redirect_after_login() {
  $redirect_url = home_url("https://wordpress.stackexchange.com/");
  if (isset($_SESSION['referer_url'])) {
    $redirect_url = $_SESSION['referer_url'];
    unset($_SESSION['referer_url']);
  }
  return $redirect_url;
}
add_filter('login_redirect', 'redirect_after_login');