Logout after clicking URL link results in “headers already sent” error

You should do redirects within a hook before content is rendered. Try running that code inside a template_redirect hooked function.

Something like this:

add_action( 'template_redirect', 'my_redirects', 5 );
function my_redirects(){
    // Your code here
}