I had this problem with two different keyboards, and have figured out a quick, consistent solution—if you detach the keyboard and flip it around so that back of the iPad is facing you, and try to force it into position and then flip it back, they keyobard will connect.
The keyboard and iPad won’t attach in the reverse position because it seems that the magnets in the keyboard and in the iPad alternate (positive-negative) so that it only connects in the forward position. But if you try to match the top and bottom (so that the central connector in the iPad and the keyboard match up), that’s should do the trick.
I tried using a magnet (as suggested in the comments above) and that worked for a while, but not consistently. I’d have to run the magnet all over the area above the numbers, finally stopping at the number (above the 1 and 2) before the keyboard would connect, but, more often over time, it would disconnect befoe I could set the iPad in the keyboard gutter.
It seems that turning the iPad around in the gutter precisely lines up the positive magnets in the iPad and in the keyboard of exactly the right size and in exactly the right places, and the negative magnets with the negative magnets so that it pushes whatever magetic switch is responsible for this problem back in place so that we you match positive and negative it’s ready to connect again.