Security fundamentals
Web security operates in layers:
- Transport security — HTTPS/TLS encryption
- Application layer — headers, input validation, authentication
- Network layer — firewall rules, rate limiting, geo-blocking
- 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 originscript-src— where JavaScript can load fromstyle-src— where CSS can load fromimg-src— image sourcesconnect-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 subdomainspreload— 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:
- Validate redirect destinations (allowlist)
- Use relative paths when possible
- Check referer for sensitive redirects
- 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