Code not working with post name Permalink Settings Help

I’m not sure why you’re getting a 404, because when I run your code with permalinks = “Post name” it runs fine.

However, I would suggest you use remove_query_arg() instead of all the machinations you’re doing to produce the URL to redirect to. That is, you can simplify your code down to:

function
affiliate_redirect ()
{
    $varname="affid" ;
    $weeks="4" ;
    if (isset ($_GET[$varname]) && '' != $_GET[$varname]) {
        setcookie ('wp_affiliate', $_GET[$varname], time () + 648000 * $weeks, "https://wordpress.stackexchange.com/") ;

        $url = remove_query_arg ($varname) ;
        wp_redirect ($url) ;

        exit ;
        }

    return ;
}

Try that and see if it doesn’t fix your 404 problem.