A computational method for optimizing both single- and two-layer surface coils is presented that is relatively easy to implement in practice using either a variational approach or through standard numerical matrix diagonalization techniques. The technique is applied, in particular, to develop a self-shielded gradiometer that is relatively immune to radiofrequency (rf) interference from distant sources with a minimal compromise to its ability to sense rf from nearby sources, properties necessary for nuclear quadrupole resonance detection of buried land mines. Results of the optimization procedure are evaluated using finite-element numerical techniques and measurements on prototype coils for a number of configurations. These results show that practical coils can be constructed that approximate the theoretically optimized coils quite well. In addition, the trade off between the surface coil sensitivity and noise immunity is presented for the self-shielded gradiometer configuration.