I know that the interaction terms of the Lagrangian of electromagnetism are given by
$$L_{int}=-q\phi (\mathbf{x},t)+q\mathbf{v}(t)\cdot \mathbf{A}(\mathbf{x},t).$$
The above equation is replaced by terms involving a continuous charge density $\rho$ and current density $\mathbf{j}$. The resulting Lagrangian density for the electromagnetic field is: $$\mathcal{L}=-\rho \phi +\mathbf{j}\cdot \mathbf{A}+\frac{\epsilon _{0}}{2}E^{2}-\frac{1}{2\mu _{0}}B^{2} .$$
The first problem is that I know where the first two terms $-\rho \phi +\mathbf{j}\cdot \mathbf{A}$ come from but I don't know where the last two terms $\frac{\epsilon _{0}}{2}E^{2}-\frac{1}{2\mu _{0}}B^{2}$ come from.
Next varying the Lagrangian density with respect to $\phi$ and $\mathbf{A}$, we get Gauss' law $$0=-\rho +\epsilon _{0}\triangledown \cdot \mathbf{E}$$ and Ampère's law $$0=\mathbf{j}+\epsilon _{0}\frac{\partial \mathbf{E}}{\partial t}-\frac{1}{\mu _{0}}\triangledown \times \mathbf{B},$$ respectively. The second problem is that I don't know how to calculate these variations clearly.