According to the Real Academia Dictionary, this word can be traced back to 19th century Carlist Wars in the form "guiristino," the pronunciation of Basque-speaking Carlist forces of the name of their enemies, the Cristinos (after regent Queen Maria Cristina).
There is a theory that it derives from Moroccan and Algerian Arabic gaouri (a word with a similar meaning applying to Europeans), which in turn stems from Ottoman Turkish gâvur [REF].