I've built an amplifier with an lm386 but when I connect a speaker (8ohm) to the output I get a very distorted signal. The problem appears only when the speaker is connected. If I connect an external amplifier to the lm386 output, the audio is right. The issue appears also without gain capacitor between pin 1 and 8 and with the most basic configuration from the datasheet (LM386 with Gain = 20, page 8 on TI datasheet)
Compare your circuit with an example from the datasheet:
You have the + input grounded rather than the - input as in the datasheet. The LM386 only works properly when the - is grounded and signal goes in the +. You have the connections to pin 2 and pin 3 swapped.
You have some strange feedback from the output to the gain input. Don't do that. The gain pins should only be connected together (through a capacitor or a capacitor in series with a resistor.) Remove R18 and C9.
The LM386 is not an opamp. It is a power amplifier whose symbol happens to resemble that of an opamp.
It doesn't work like an opamp, and you can't treat it as one.
Looks like you are using this circuit:
You should leave pin 8 open in that case, and apply the input signal to pin 3.
If you don't want the bass boost, use one of the other circuits in the datasheet.