A number of obstacles, including irrigated wastewater and soil contamination, arise in the growth of aromatic and medicinal plants. This study aimed to reduce the effects of contaminated soil and wastewater irrigation on rosemary (Rosmarinus officinalis L.) plants by using biosynthesized silver nanoparticles (AgNPs) produced by the ginger (Zingiber officinale) plant extract. The AgNPs were characterized using Attenuated Total Reflection Fourier Transform Infrared (ATR-FTIR). The experimental design involved three distinct groups of plants: one group was irrigated with regular tap water, another group was rooted in soil contaminated by sewage-wastewater and irrigated with processed wastewater, and the final group consisted of plants grown in wastewater-contaminated soil, irrigated with processed wastewater, and sprayed with 200 mM l−1 AgNPs. The study also examined the impact of different treatments on gene expression and secondary metabolite levels in rosemary plants. According to HPLC investigations, nineteen phenol compounds and flavonoids were identified in a methanolic extract of rosemary that was grown in contaminated soil, irrigated with wastewater, and sprayed with AgNPs. Plants treated with wastewater and nanoparticles produced quantities of secondary compounds, including resvertol, vanillic acid, and gallic acid with 1.11, 0.15, and 0.01 mg g−1 respectively, which are all regarded as significant antioxidants employed in the pharmaceutical industry. Hexokinase synthase (HK), geranyl diphosphate synthase (GPPS), and linalool synthase (LS) coding genes were found to have highly expressed expressions when plants grown in contaminated soil, wastewater-irrigated plants, and nanoparticle-sprayed plants, respectively, at a 23.2- and 5.54-fold level, where the HK gene was 8.7 times more strongly expressed. Conversely, plants grown in contaminated soil and irrigated with treated wastewater showed downregulation of these genes. Conclusively, using silver nanoparticles significantly reduced the influence of wastewater pollution on secondary metabolites in rosemary plants, which was increased by the gene expression results and was completely consistent with HPLC analysis.