Protect your website from malware and vulnerabilities

How sites actually get compromised, the habits that prevent it, and what to do in the first hour if it happens to you.

A cream shield on a terracotta base with a plant growing behind it

Most website compromises are not targeted. Automated scanners crawl the internet looking for a known flaw in a plugin, an exposed admin page or a reused password, and they try every site they find. If yours has the flaw, it gets hit.

This guide is for developers and site owners who run a web app or a WordPress site and want a practical routine rather than a theory lesson. By the end you will know the common ways sites are broken into, how to keep dependencies patched automatically, which HTTP security headers to send, and exactly what to do if you find malware on your site.

Server hardening (SSH, firewalls, OS updates) is covered separately in How to secure a cloud server. This article focuses on the application itself.

How websites get compromised

Attackers rarely need anything clever. These five routes account for most incidents:

  • Outdated plugins, themes and dependencies. Once a vulnerability is published, scanners start probing for it within days. A site running an old version of a popular plugin or library is an easy target.
  • Weak or reused credentials. Admin panels, database users and hosting dashboards protected by a short or reused password fall to credential stuffing, where leaked username and password pairs from other breaches are tried automatically.
  • Injection. When user input is pasted straight into an SQL query, a shell command or a template, an attacker can make your app run their instructions. SQL injection is the classic example.
  • Cross-site scripting (XSS). If your app shows user-supplied text without escaping it, an attacker can plant JavaScript that runs in other visitors' browsers, stealing sessions or redirecting them.
  • Supply chain attacks. A package you depend on is hijacked, or a lookalike package name is published, and malicious code arrives through a normal install.

Malware is usually the result of one of these: spam pages, redirects, card-skimming scripts or a server sending junk email.

Keep dependencies patched

Patching is the single most effective habit, so make it routine.

Audit what you already have

Each ecosystem has a built-in or standard audit tool that checks your lockfile against a database of known vulnerabilities:

Terminal
# Node.js: report known vulnerabilities, then apply compatible fixes
npm audit
npm audit fix

# Only production dependencies
npm audit --omit=dev

# Python: install the auditing tool, then check your requirements
pip install pip-audit
pip-audit -r requirements.txt

# PHP (Composer 2.4 or later)
composer audit

npm audit fix only applies updates that stay within the version ranges in your package.json. Fixes that need a major version bump are listed separately; read the changelog before forcing them with --force.

Automate updates with Dependabot

If your code is on GitHub, Dependabot can open a pull request whenever a dependency has an update. Add this file at .github/dependabot.yml:

YAML
version: 2
updates:
  - package-ecosystem: "npm"
    directory: "/"
    schedule:
      interval: "weekly"
    open-pull-requests-limit: 5
  - package-ecosystem: "pip"
    directory: "/"
    schedule:
      interval: "weekly"
  - package-ecosystem: "composer"
    directory: "/"
    schedule:
      interval: "weekly"
  - package-ecosystem: "github-actions"
    directory: "/"
    schedule:
      interval: "weekly"

Keep only the ecosystems your project uses. Pair this with automated tests (see CI/CD with GitHub Actions) so you can merge update pull requests with confidence instead of letting them pile up.

Send security headers

Security headers tell the browser to apply extra protections. They cost nothing and block whole classes of attack.

HeaderWhat it does
Content-Security-PolicyLists where scripts, styles and images may load from. Limits the damage of XSS.
Strict-Transport-SecurityTells browsers to use HTTPS only for your domain, for the time you set.
X-Content-Type-Options: nosniffStops browsers guessing file types, so an upload can't be run as a script.
Referrer-PolicyControls how much of the current URL is sent to other sites when visitors click links.

Here is a minimal Express middleware that sets all four without extra packages:

JavaScript
app.use((req, res, next) => {
  res.setHeader(
    "Content-Security-Policy",
    "default-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'"
  );
  res.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
  res.setHeader("X-Content-Type-Options", "nosniff");
  res.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
  next();
});

The helmet package for Express sets a sensible group of headers for you, and most frameworks have an equivalent setting or middleware.

Only send Strict-Transport-Security once HTTPS works on every subdomain you include, because browsers will refuse plain HTTP for the whole max-age period.

Validate input and escape output

Treat every value that arrives from a browser, an API client or a webhook as untrusted.

  • Use parameterised queries or your ORM's query builder. Never build SQL by joining strings.
  • Validate on the server, even if the form already validates in the browser. Check type, length and allowed characters.
  • Escape output using your template engine's default escaping. Avoid features that insert raw HTML (dangerouslySetInnerHTML, |safe, {!! !!}) unless the content has been sanitised.
  • Restrict uploads by type and size, store them outside the code folder, and never run them.

A parameterised query in Python looks like this, with the driver handling the escaping:

Python
cur.execute("SELECT id, name FROM customers WHERE email = %s", (email,))

Add a web application firewall

A web application firewall (WAF) inspects requests before they reach your app and blocks known attack patterns, such as common SQL injection strings or requests for well-known exploit paths. A service such as Cloudflare can sit in front of your site and do this at the edge; see Cloudflare explained.

A WAF is an extra layer, not a replacement for patching: it cannot know about flaws in your own code.

Signs your site has been compromised

  • Pages or links you didn't create, often spam in other languages, showing up in search results.
  • Visitors (especially on mobile or arriving from search) redirected to other sites.
  • Unknown admin users, or plugins and files you didn't add.
  • New scripts in your pages loading from unfamiliar domains, especially on checkout pages.
  • A sudden spike in outgoing email, CPU use or traffic.
  • A browser or search engine warning that the site is unsafe.

Step by step: responding to a compromise

Work through this in order. Speed matters, but so does not destroying the evidence you need.

  1. Isolate. Take the site offline or put it in maintenance mode so it stops harming visitors. On Launchpad you can stop the app from its dashboard.
  2. Record what you see. Note the time, save suspicious files and copy relevant log lines before you change anything.
  3. Rotate every secret. Change admin passwords, database passwords, API keys, payment keys and tokens. Assume anything the app could read has been copied. On Launchpad, update values in the Variables tab and press Redeploy now.
  4. Restore from a clean backup. Pick a backup from before the first sign of trouble. Redeploy your code from a known-good commit in your repository rather than trusting files on the server. Launchpad backups cover the app's /data folder and connected PostgreSQL or MySQL databases, and a restore takes a "Before a restore" backup first so you can undo it; see Back up and restore.
  5. Patch the hole. Update the plugin or dependency that let the attacker in, remove anything unused, and fix the code if the cause was injection or XSS. Restoring without patching just resets the clock.
  6. Review. Check logs and access records for how they got in and what they touched. On Launchpad, the app's Activity tab shows actions taken on the app. If personal data may have been exposed, check your legal obligations to notify customers or regulators.
  7. Bring the site back and watch it. Monitor closely for the next few days in case something was missed.

WordPress specifics

WordPress itself is well maintained; most WordPress compromises come through plugins and themes.

  • Keep core, plugins and themes updated, and turn on automatic updates for plugins you trust.
  • Delete plugins and themes you don't use. Deactivated code can still be exploited.
  • Install plugins only from the official directory or reputable vendors. Never use "nulled" (pirated) premium plugins, which often contain backdoors.
  • Give each person their own account with the lowest role that works, and use two-factor authentication for admins.
  • Add define('DISALLOW_FILE_EDIT', true); to wp-config.php to remove the built-in theme and plugin file editor.

For hosting setup, see Host WordPress on Launchpad.

Common mistakes

  • Running npm audit once and never again. Fix: automate with Dependabot and review its pull requests weekly.
  • Restoring a backup without finding the cause. Fix: patch the entry point before bringing the site back, or it will be reinfected.
  • Restoring a backup that is already infected. Fix: pick a backup from before the earliest sign of compromise, and keep enough history to go back far enough.
  • Forgetting secrets after an incident. Fix: rotate every password and key the app could read, not just the admin login.
  • Enforcing a strict CSP straight away. Fix: use report-only mode first and add the sources you actually need.

Security notes

  • Never commit secrets to your repository. Use environment variables; see Environment variables and secrets.
  • Lock your dependency versions with a lockfile and install with npm ci or equivalent so builds are repeatable.
  • Before adding a new package, check that the name is spelled correctly and that it is actively maintained.
  • Use a password manager and two-factor authentication for every dashboard that controls your site, including your domain registrar.

Troubleshooting

SymptomLikely causeFix
Scripts or styles stopped loading after adding headersContent-Security-Policy blocks their sourceAdd the domain to the relevant directive, or move inline scripts into files
npm audit fix leaves vulnerabilitiesFix needs a major version updateRead the changelog, update manually and test
Dependabot opens no pull requestsFile in the wrong place or invalid YAMLCheck the path is .github/dependabot.yml and validate indentation
Malware returns after a restoreThe vulnerability wasn't patched, or the backup was infectedPatch first, then restore an older backup
Site shows mixed-content warnings after HSTSPages still load assets over http://Change asset URLs to https:// or relative paths

Frequently asked questions

Is a security plugin enough for WordPress?

It helps, but it can't fix an outdated plugin it doesn't know about or a weak admin password. Updates, fewer plugins and strong logins matter more.

How often should I update dependencies?

Review updates at least weekly and apply security fixes as soon as they are published for anything internet-facing. Automating the pull requests makes this a short routine.

Does HTTPS protect my site from malware?

No. HTTPS encrypts traffic between visitors and your site, so it stops eavesdropping and tampering in transit. It does nothing about a vulnerable plugin or injected code on the server.

Should I clean infected files or restore a backup?

Restore a clean backup and redeploy code from your repository wherever you can. Cleaning by hand is slow and it is easy to miss a backdoor.

Next steps

Security is a routine, not a project: automate updates, send the right headers, validate input and keep a tested way back. Practise a restore before you need one.

Share this articleLinkedIn (opens in a new tab)X (opens in a new tab)Facebook (opens in a new tab)
Was this article helpful?

Get new guides in your inbox.

One email a month. Unsubscribe anytime.