CSP Generator — Free Content Security Policy Header Generator

Build a correct Content-Security-Policy header in minutes: a visual directive builder, a real nonce & SHA-256/384/512 hash generator, a validator that catches 20+ misconfigurations, and copy-paste deployment snippets for WordPress, nginx, Apache, IIS, Express, and Laravel. Free forever, no signup — everything runs 100% in your browser, nothing is uploaded anywhere.

Generated policy


Nonce & hash generator

Two ways to allow a specific inline script or style without 'unsafe-inline':

Nonce ('nonce-…')
Your server generates a fresh random value per request, puts it in the header and in the tag: <script nonce="abc…">. One token covers all inline scripts. Requires server-side rendering.
Hash ('sha256-…')
Computed from the exact bytes of the inline script. Works on fully static/cached pages — the script never changes, so the hash stays valid. Paste the script body below.
🔒 Honest crypto note: hashes are computed with the Web Crypto API (SHA-256/384/512) directly in your browser — the same algorithms openssl dgst uses. Nonces shown here are random demo values; on a real site your server must generate a new nonce on every request and inject it into both the header and the HTML.

1. Generate a hash of inline code

Hashes will appear here…

2. Generate a nonce

Nonce will appear here…

CSP validator

Paste an existing policy. The validator checks 20+ misconfiguration patterns: typos, contradictory 'none', bare 'unsafe-inline', 'strict-dynamic' without nonce/hash, wildcard/data:/http: sources, missing object-src/base-uri/frame-ancestors, deprecated directives, sandbox footguns, and more.

Presets

One click loads a preset into the Builder. Every preset serializes through the same spec-correct engine and is re-validated before display.

🔒 Strict preset honesty: it emits 'nonce-{NONCE}' as a placeholder — a static tool cannot rotate nonces for you. Your server must generate a fresh 128-bit nonce per request and substitute it in both the header and each <script nonce="…"> tag. The validator understands this placeholder.

What is a Content Security Policy?

A Content Security Policy (CSP) is an HTTP response header — Content-Security-Policy — that tells the browser exactly which sources a page may load scripts, styles, images, fonts, frames, and connections from. It is the single most effective XSS (cross-site scripting) mitigation available: even if an attacker manages to inject markup into your page, the browser refuses to run scripts from sources you never allowed.

A minimal policy looks like this:

Content-Security-Policy: default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'

Each directive (default-src, script-src, …) carries a list of allowed sources: 'self' (your own origin), 'none' (nothing), host names, https:, data:, nonces, and hashes. Anything not listed is blocked and reported.

Directive reference — what each one stops

DirectiveControlsAttack it prevents
default-srcFallback for all unset fetch directivesBaseline for everything — without it there is no default deny
script-srcWhich scripts may executeXSS — the main event. No attacker scripts, no payload
style-srcStylesheets & inline stylesCSS-based data exfiltration, UI redressing helpers
img-srcImagesTracking pixels from attacker domains
connect-srcfetch / XHR / WebSocket / EventSourceData exfiltration to attacker servers
font-srcWeb fontsMalicious font parsing exploits
frame-srcEmbedded framesMalicious iframes, drive-by content
frame-ancestorsWho may embed your pageClickjacking — replaces X-Frame-Options
object-src<object> / <embed>Legacy plugin XSS — set to 'none'
base-uri<base> tag URLBase-tag injection hijacking relative URLs
form-actionWhere forms may submitCredential harvesting via injected forms
worker-srcWorkers / ServiceWorkersPersistent attacker code via service worker
upgrade-insecure-requestsAuto-upgrades http: → https:Mixed-content tampering
report-uri / report-toViolation report endpointVisibility — you can't fix what you can't see

Deploying your policy — platform guides

WordPress

WordPress core, themes, and plugins rely heavily on inline scripts, so a strict policy will break the admin area. Workflow: (1) generate the WordPress preset above, (2) deploy it as Content-Security-Policy-Report-Only first, (3) watch violation reports for 1–2 weeks and allowlist what your plugins legitimately need, (4) switch to enforcing. Send the header from your server config or with header('Content-Security-Policy: …') in PHP (or a security plugin).

nginx

Add inside server or location (on Linux, typically under /etc/nginx/) and reload: add_header Content-Security-Policy "…" always; — the always parameter ensures the header is sent on error responses too. Use the nginx output format above for the exact snippet.

Apache

Header always set Content-Security-Policy "…" in your virtual host or .htaccess (requires mod_headers). The Apache output format generates it verbatim.

IIS (web.config)

Add a <customHeaders> entry under system.webServer/httpProtocol, or set it in IIS Manager → HTTP Response Headers. Use the IIS output format for the XML snippet.

Express / Node.js

Set the header in middleware with res.setHeader('Content-Security-Policy', '…') — or use the helmet npm package, which manages CSP (including per-request nonces) for you. The Express output format gives you the middleware snippet.

Laravel / PHP

Attach the header in middleware: return $next($request)->header('Content-Security-Policy', '…'); — or use spatie/laravel-csp for nonce support. The Laravel output format generates the snippet.

Next.js

Set headers in next.config.js under async headers() for the /(.*) source. For nonces, use Next.js middleware to generate a per-request value and pass it via request.headers.

HTML <meta> tag

<meta http-equiv="Content-Security-Policy" content="…"> works when you can't touch server config (static hosting, some CMS themes) — but frame-ancestors, report-uri, report-to, and sandbox are silently ignored in meta tags. Prefer the header.

Spring Boot / Java & Python (Django/Flask)

Same header, different plumbing: Spring Security's headers().contentSecurityPolicy("…"), Django via django-csp middleware, Flask by setting the header in after_request. The policy syntax this tool generates is identical everywhere — only the delivery mechanism changes.

More use cases & platform notes

Chrome extensions (Manifest V3): extensions declare their own policy via the content_security_policy key in manifest.json (extension_pages and sandbox contexts) — remote scripts are banned entirely there, so generate hashes for any bundled inline code.

Mobile apps & WebViews (Android/iOS): a CSP delivered by your web server also applies inside Android WebView and iOS WKWebView. Keep connect-src tight — it governs what API endpoints your hybrid app can reach.

Blogs: the Balanced preset fits most blogs — allow your theme's hosts plus https: for embeds, then tighten with report-only data.

Google Analytics 4: GA4 needs script-src access to www.googletagmanager.com and connect-src to www.google-analytics.com — add both as custom hosts in the Builder rather than opening https: wholesale.

Local development: allow localhost:* / 127.0.0.1:* in connect-src and script-src while developing, and strip them before deploying to production.

Microsoft Edge: Edge enforces the same CSP core as Chrome (both Chromium) — test your policy in Edge, Firefox, and Safari, since Safari lags on Level 3 features.

Libraries: third-party JavaScript libraries — any library like jQuery, an analytics snippet, or a chat widget — are the usual reason policies need https: or extra hosts. See the directive reference table above for concrete examples of what each directive allows.

This page doubles as a step-by-step tutorial: the rollout playbook above summarizes CSP best practices — the core principle is default-deny with explicit allowlists. Review your policy in the Validator tab after every deploy that adds scripts (Next.js — often searched as "nextjs" — nodejs/Express, TypeScript builds included — CSP applies to the served JavaScript, whatever compiled it).

Rollout playbook (so your CSP doesn't break production)

  1. Generate a policy with the Builder, starting from the Balanced or WordPress preset.
  2. Validate it in the Validator tab — fix every error, read every warning.
  3. Deploy as Report-Only (Content-Security-Policy-Report-Only) with a report-uri collector for 1–2 weeks.
  4. Triage reports: allowlist legitimate third parties (analytics, CDNs, payment widgets); investigate anything unexpected — it may be an actual injection attempt.
  5. Switch to enforcing, keep reporting on, and re-validate after every deploy that adds scripts.

Troubleshooting "not working": open Chrome or Firefox DevTools → Console. Every blocked resource logs a precise violation naming the directive and the blocked URL — add the missing source and redeploy. Edge and Firefox enforce the same core; Safari lags on some Level 3 features (navigate-to, parts of Trusted Types), so test there too.

How this generator compares

ToolTypeWhat it does wellWhere this generator wins
This generator (nrtechstudio.com)Web appVisual builder, real nonce/hash crypto, validator, framework presets, SEO guides—
Google CSP EvaluatorWeb appExcellent at evaluating an existing policyIt's an evaluator, not a generator — it won't build you a policy or emit server snippets
csp-builder (GitHub Pages single HTML)Web appDecent checklist UINo framework presets, no nonce/hash generation, no validator, no guides or SEO content
CLI/crawler generators (HashCSP, csp-gen, …)CLI / server-sideAuto-discover sources by crawling your siteRequire installing/running code and server access; different intent (crawl vs. guided builder)
MDN CSP docsDocumentationThe authoritative referenceNot a tool — no builder, no validation, no snippets

Comparison is factual to the best of our knowledge as of October 2026; features change — verify before choosing.

Frequently asked questions

What is a Content Security Policy (CSP)?A Content Security Policy is an HTTP response header (Content-Security-Policy) that tells the browser exactly which sources of scripts, styles, images, fonts, and other resources a page is allowed to load. It is the single most effective mitigation against cross-site scripting (XSS): even if an attacker injects markup, the browser refuses to execute scripts from sources you did not allow.
How do I generate a CSP header with this tool?Use the Builder tab: tick allowed sources per directive (default-src, script-src, style-src, img-src, and more), pick an output format (HTTP header, meta tag, nginx, Apache, IIS, Express, or Laravel snippet), then copy the result. Start from a preset (Strict, Balanced, WordPress, or Report-Only) and adjust.
What is the difference between report-only and enforcing mode?Enforcing mode (Content-Security-Policy) blocks violating resources. Report-only mode (Content-Security-Policy-Report-Only) only logs violations to your report-uri/report-to endpoint without blocking anything. Best practice: run report-only for 1–2 weeks, fix every legitimate violation, then switch to enforcing.
Should I use a nonce or a hash for inline scripts?Use a nonce ('nonce-…') when your server can generate a fresh random value per request — it covers all inline scripts with one token. Use a hash ('sha256-…') when the inline script never changes (e.g. a static analytics snippet): compute the hash of the exact script body with the Hash tab. Never reuse a nonce across requests.
Why is 'unsafe-inline' dangerous?'unsafe-inline' permits every inline <script> and event handler on the page — exactly what XSS payloads use. A policy with script-src 'unsafe-inline' stops almost no XSS. Replace it with nonces or hashes; keep 'unsafe-inline' only as a legacy-browser fallback alongside 'strict-dynamic'.
What does 'strict-dynamic' do?'strict-dynamic' lets scripts explicitly trusted (via nonce or hash) load further scripts dynamically, while ignoring the host allowlist. It simplifies policies for modern apps — but it only works when paired with a nonce or hash, and only in browsers that support CSP Level 3.
How do I add a Content Security Policy to WordPress?Add the header in your server config (nginx add_header, Apache Header set) or via a security plugin, or send it from PHP with header("Content-Security-Policy: …"). WordPress core, themes, and plugins rely heavily on inline scripts, so start with the WordPress preset in report-only mode and tighten gradually.
How do I add CSP in nginx, Apache, or IIS?nginx: add_header Content-Security-Policy "…" always; inside server or location. Apache: Header always set Content-Security-Policy "…". IIS: add a custom HTTP response header in web.config or IIS Manager. This tool's output-format selector generates each snippet for you.
Can I use a <meta> tag instead of an HTTP header?Yes, with limits: <meta http-equiv="Content-Security-Policy"> works for most fetch directives, but frame-ancestors, report-uri, report-to, and sandbox are ignored in meta tags. Prefer the HTTP header whenever you control the server.
frame-ancestors vs X-Frame-Options — which should I use?Use frame-ancestors 'self' (or your allowlist) — it is the CSP replacement for X-Frame-Options and supports multiple origins. Keep X-Frame-Options: SAMEORIGIN as well for very old browsers that predate CSP.
Does CSP stop all XSS attacks?No — CSP is defense in depth, not a cure. It cannot fix stored XSS that exfiltrates via allowed endpoints, and a policy with 'unsafe-inline' or '*' in script-src stops almost nothing. Combine CSP with output encoding, Trusted Types, and secure coding.
My CSP is blocking legitimate resources. How do I troubleshoot?Open Chrome/Firefox DevTools console: every blocked resource logs a precise violation naming the directive and the blocked URL. Switch to Content-Security-Policy-Report-Only while fixing, add the missing sources, then use this tool's Validator tab to catch typos and misconfigurations.
What is the difference between CSP Level 2 and Level 3?Level 3 adds 'strict-dynamic', 'unsafe-hashes', 'report-to' (Reporting API), worker-src, navigate-to, and Trusted Types integration. All modern browsers support the Level 2 core (nonces, hashes, frame-ancestors); use Level 3 features with graceful fallbacks.
How do I use nonces on a static or cached site?True nonces require per-request server rendering — impossible on fully static/cached pages. On static sites, use hashes ('sha256-…') for each inline script instead: the script body never changes, so the hash stays valid behind any cache.
Where do CSP violation reports go?Browsers POST a JSON report to the URL in report-uri (widely supported, deprecated in CSP3) or report-to (CSP3, via the Reporting API). Point it at your own collector endpoint or a reporting service, and monitor it during rollout.

Privacy & security notes

This generator is 100% client-side: your policy drafts, inline scripts, and hashes never leave your browser — there is no server to send them to. Hashes use the Web Crypto API (the same SHA-256/384/512 your OS ships). The tool is defensive by design: it helps you harden websites against XSS and clickjacking, and the validator actively warns against weak configurations.

Free tool by NRTechStudio