Security fundamentals

Web security operates in layers:

  1. Transport security — HTTPS/TLS encryption
  2. Application layer — headers, input validation, authentication
  3. Network layer — firewall rules, rate limiting, geo-blocking
  4. Physical layer — server access controls

No single measure is perfect. Defense in depth means multiple overlapping protections.

Security headers

HTTP headers tell browsers how to handle your content securely:

Content-Security-Policy (CSP)

Controls what resources (scripts, styles, images) can load. Prevents XSS attacks:

Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'

Start restrictive and relax as needed. Common directives:

  • default-src 'self' — only load resources from same origin
  • script-src — where JavaScript can load from
  • style-src — where CSS can load from
  • img-src — image sources
  • connect-src — AJAX/WebSocket endpoints

Strict-Transport-Security (HSTS)

Forces HTTPS for future visits:

Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
  • max-age — how long to remember (seconds)
  • includeSubDomains — apply to all subdomains
  • preload — eligible for browser preload lists

Warning: Once set with long max-age, you must maintain valid HTTPS. No turning back without waiting for expiry.

X-Frame-Options

Prevents your site being embedded in iframes (clickjacking protection):

X-Frame-Options: DENY

Or allow only same origin:

X-Frame-Options: SAMEORIGIN

X-Content-Type-Options

Prevents MIME-type sniffing:

X-Content-Type-Options: nosniff

Browsers won't guess content types, reducing XSS risks.

TLS basics

TLS (Transport Layer Security) encrypts connections between browsers and servers.

Certificate requirements

  • Valid certificate from trusted CA (Let's Encrypt is free)
  • Covers all domains/subdomains you serve
  • Renewed before expiry (typically 90 days for Let's Encrypt)

Configuration best practices

  • Disable old protocols: TLS 1.0 and 1.1 are deprecated
  • Use TLS 1.2+ only: preferably TLS 1.3
  • Strong ciphers: prefer AEAD ciphers (AES-GCM, ChaCha20-Poly1305)
  • HTTP to HTTPS: 301 redirect all HTTP traffic

Test your TLS configuration: SSL Labs

Redirect safety

Open redirect vulnerabilities occur when your site redirects users to arbitrary URLs:

Bad: https://example.com/redirect?url=https://evil.com

Prevention:

  1. Validate redirect destinations (allowlist)
  2. Use relative paths when possible
  3. Check referer for sensitive redirects
  4. Never trust user input in redirect targets

Safe configuration principles

  • Principle of least privilege — only grant minimum necessary access
  • Default deny — block everything, then allow specific exceptions
  • Fail securely — errors should not bypass security
  • Defense in depth — multiple overlapping protections
  • Regular updates — patch known vulnerabilities promptly