Security Headers Configuration Guide: CSP / HSTS / X-Frame-Options

HTTP security headers are the first line of browser-side defense. Proper configuration effectively prevents XSS, clickjacking, MIME sniffing, and other attacks.

1. Core Security Headers

1.1 Content-Security-Policy (CSP)

The strongest defense against XSS and injection attacks.

add_header Content-Security-Policy "
    default-src 'self';
    script-src 'self' 'unsafe-inline' https://trusted-cdn.com;
    style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
    img-src 'self' data: https:;
    font-src 'self' https://fonts.gstatic.com;
    connect-src 'self' https://api.example.com;
    frame-src 'self';
    object-src 'none';
    base-uri 'self';
    form-action 'self';
" always;

CSP Deployment Strategy:

Phase 1: Report-only mode (observe violations)
Phase 2: Relaxed policy (gradually tighten)
Phase 3: Strict policy (remove unsafe-inline)

1.2 Strict-Transport-Security (HSTS)

Tells browsers to always use HTTPS.

# Production (1 year)
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

1.3 X-Frame-Options

Prevents clickjacking attacks.

add_header X-Frame-Options "DENY" always;
# or
add_header X-Frame-Options "SAMEORIGIN" always;

1.4 X-Content-Type-Options

Prevents MIME sniffing.

add_header X-Content-Type-Options "nosniff" always;

1.5 Referrer-Policy

Controls referrer information.

add_header Referrer-Policy "strict-origin-when-cross-origin" always;

1.6 Permissions-Policy

Controls browser API permissions.

add_header Permissions-Policy "geolocation=(), microphone=(), camera=(), payment=()" always;

2. Complete Security Headers Configuration

Nginx

add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
add_header Permissions-Policy "geolocation=(), microphone=(), camera=(), payment=()" always;

3. Validation Tools

  1. Security Headers (securityheaders.com)
  2. Mozilla Observatory (observatory.mozilla.org)
  3. CSP Evaluator (csp-evaluator.withgoogle.com)

4. Common Issues

  • CSP too strict blocking third-party scripts
  • HSTS causing local dev environment issues

5. Summary

HTTP security headers are among the most cost-effective security measures. Start with X-Frame-Options, X-Content-Type-Options, and Referrer-Policy, then gradually deploy CSP and HSTS.