Security

How to Protect a Website from Attacks: SQL Injection, XSS, Brute Force and DDoS

By NileVPS Team · Published · 5 min read

اقرأ المقال بالعربي

Most websites are not attacked because someone chose them personally. They are attacked because automated tools scan the internet for known weaknesses: an outdated plugin, a login page without limits, a form that passes input straight to the database. Knowing how common attacks work makes defense easier, because the fixes are well known. This guide covers four attack families every site owner should know, SQL injection, cross-site scripting, brute-force logins and denial of service, with practical defenses for sites hosted on a VPS.

SQL injection (SQLi)

SQL injection happens when user input is glued directly into a database query. Consider this vulnerable PHP code:

$sql = "SELECT * FROM users WHERE email = '" . $_POST['email'] . "'";

If an attacker submits ' OR '1'='1 as the email, the query logic changes and may return every user. More elaborate payloads can read entire tables or, in some configurations, modify data.

Defenses:

  • Use prepared statements (parameterized queries) for every query that includes input. The database then treats input strictly as data, never as SQL:
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$_POST['email']]);
  • Prefer your framework's query builder or ORM, which parameterizes by default.
  • Give the application's database user only the permissions it needs; it should not be able to drop tables or read other databases.
  • Never show raw database errors to visitors. Log them instead.

Cross-site scripting (XSS)

XSS happens when a site displays user-supplied content without escaping it, so the browser executes it as code. A comment containing <script> that runs for every visitor could steal session cookies, redirect users or change what the page shows.

Defenses:

  • Escape output according to context. In PHP, htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); template engines such as Blade, Twig and React escape by default, so be careful with features that disable escaping.
  • Validate input: if a field should be a number or an email, reject anything else.
  • Mark session cookies as HttpOnly, Secure and SameSite=Lax so scripts cannot read them and they are not sent over plain HTTP.
  • Add a Content Security Policy header that limits where scripts can load from. Start in report-only mode to avoid breaking the site:
add_header Content-Security-Policy-Report-Only "default-src 'self'" always;

Brute-force and credential stuffing

Bots try thousands of password combinations, or reuse username and password pairs leaked from other sites, against login pages like /wp-login.php or /admin.

Defenses:

  • Require strong, unique passwords and offer two-factor authentication for admin accounts.
  • Limit login attempts per IP and per account. In Nginx, a simple rate limit on the login path looks like this:
# in the http block
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;

# in the server block
location = /wp-login.php {
    limit_req zone=login burst=5 nodelay;
    # ... your existing PHP handling
}
  • Use fail2ban with a jail that reads your web server or application logs to ban repeat offenders.
  • Restrict admin areas by IP or put them behind a VPN when practical.

The same principles apply to server access itself; our guide on securing SSH with keys shows how.

Denial of service (DoS and DDoS)

A denial-of-service attack tries to make a site unavailable by exhausting resources: network bandwidth, connections, CPU or the database. A distributed attack (DDoS) uses many machines at once.

It helps to separate two kinds:

TypeWhat it targetsWhere it is mitigated
Volumetric (UDP floods, amplification)Network bandwidthUpstream: provider network, DDoS protection service, CDN
Protocol (SYN floods)Connection tablesKernel settings such as SYN cookies, upstream filtering
Application layer (HTTP floods)CPU, PHP workers, databaseCaching, rate limiting, WAF, CDN

Practical steps on a VPS:

  • Put a CDN or reverse proxy service in front of public sites so that static content and many attacks are absorbed before they reach your server.
  • Cache aggressively; a page served from cache costs a fraction of a page generated by PHP and the database.
  • Apply rate limiting (limit_req, limit_conn) on expensive endpoints such as search, login and APIs.
  • Close every port you do not need with a firewall; see firewall explained.
  • Have monitoring and alerts so you know immediately when traffic spikes.

No single VPS can absorb a large volumetric attack on its own, so for high-profile sites, upstream protection is essential.

The foundation: updates and least privilege

Many breaches skip clever attacks entirely and exploit a known vulnerability in an outdated CMS, theme or plugin. Keep the core software and every extension updated, remove plugins you no longer use, and run the site under its own system user with write access only where it is truly needed, such as the uploads directory. Block execution of scripts inside upload folders, and keep regular off-server backups so you can recover quickly if something gets through.

Website security checklist

  • Prepared statements for all database queries
  • Output escaping and a Content Security Policy
  • Secure, HttpOnly, SameSite cookies
  • Login rate limiting, strong passwords and 2FA for admins
  • HTTPS everywhere with HSTS
  • CMS, plugins and server packages updated
  • Firewall with only 22, 80 and 443 open
  • Caching and a CDN in front of public pages
  • Tested off-server backups

A VPS gives you full control to apply every item on this list. Compare plans on our pricing page.

FAQ

Is a web application firewall (WAF) enough to protect my site?

A WAF is a useful extra layer that blocks many known attack patterns, but it cannot fix vulnerable code and it can be bypassed. Treat it as a complement to secure coding, updates and least privilege, not a replacement.

How do I know if my website has been attacked?

Warning signs include unknown admin users, unfamiliar files in upload or theme folders, unexpected redirects, spam pages in search results, sudden resource spikes and long runs of failed logins in your logs. Regular log review and file-change monitoring help you notice early.

Can I stop DDoS attacks with server settings alone?

Server settings help against small application-layer floods, through caching, rate limits and SYN cookies. Large volumetric attacks fill the network link before your configuration is involved, so they must be filtered upstream by the network provider, a protection service or a CDN.

Related guides