# What Is Content Security Policy (CSP)? A Complete Website Security Guide
## Introduction
Website security is an important part of running any online business, application, blog, or web platform. Every day, websites face different types of cyber threats, including Cross-Site Scripting (XSS), malicious JavaScript injection, data theft, and unauthorized content loading.
One important security mechanism that helps protect websites against these threats is Content Security Policy (CSP).
Content Security Policy is a browser security feature that allows website owners to control which sources are trusted for loading scripts, stylesheets, images, fonts, frames, and other resources. It works through an HTTP response header and helps reduce the risk of certain client-side attacks.
In this guide, you will learn what Content Security Policy is, how it works, why it matters, how to configure a CSP header, common mistakes to avoid, and how to test your website's CSP configuration.
## 1. What Is Content Security Policy (CSP)?
Content Security Policy (CSP) is a browser security standard that helps website owners control the resources a browser is allowed to load on a webpage.
For example, a website may allow JavaScript only from its own domain and a specific trusted service. If an attacker injects a script from an unknown external website, a correctly configured CSP may prevent the browser from executing it.
CSP is mainly designed to reduce the impact of Cross-Site Scripting (XSS) and certain content-injection attacks.
It is usually configured using an HTTP response header:
Content-Security-Policy
A website can also define a policy using an HTML meta element, but an HTTP response header is generally preferred because it supports more policy features.
## 2. Why Is Content Security Policy Important?
Modern websites load many different resources. These may include JavaScript files, CSS files, images, fonts, videos, advertisements, analytics scripts, and third-party services.
If an attacker manages to inject malicious content into a webpage, the browser may execute it unless suitable protections are in place.
CSP adds another layer of protection by restricting where webpage resources can come from.
Important benefits include:
- Helps reduce the risk of Cross-Site Scripting (XSS).
- Controls which domains can provide JavaScript.
- Restricts unauthorized external resources.
- Helps prevent malicious content from being loaded.
- Provides control over embedded frames and website connections.
- Can report policy violations for security monitoring.
- Improves the overall browser-side security strategy.
CSP is a defence-in-depth security control. It does not replace secure coding, input validation, output encoding, authentication security, or regular vulnerability testing.
## 3. How Does CSP Work?
When a browser requests a webpage, the web server sends an HTTP response. That response can include a Content-Security-Policy header.
The browser reads the policy and applies its rules while loading the page.
For example, imagine a website has this policy:
Content-Security-Policy: default-src 'self'
This tells the browser to use the website's own origin as the default permitted source for resource types covered by default-src.
If a page attempts to load a resource from an external domain, the browser checks the relevant CSP directive. If that resource is not permitted by the policy, the browser blocks it.
The browser may also report the violation in its developer console or send a report to a configured reporting endpoint.
This means CSP enforcement happens in the visitor's browser, based on the policy delivered by the website.
## 4. Important CSP Directives You Should Know
CSP contains different directives. Each directive controls a particular type of resource or browser behavior.
### 4.1 default-src
The default-src directive provides a fallback source list for several resource directives when they are not separately defined.
Example:
default-src 'self';
This generally restricts covered resources to the same origin as the website.
### 4.2 script-src
The script-src directive controls which sources are allowed to provide JavaScript.
Example:
script-src 'self';
This permits scripts from the same origin, subject to the policy's other rules.
It is one of the most important directives for reducing the risk of injected JavaScript.
### 4.3 style-src
The style-src directive controls permitted CSS sources.
Example:
style-src 'self';
If your website uses an external font or stylesheet provider, you may need to allow its exact trusted origin.
### 4.4 img-src
The img-src directive controls where images can be loaded from.
Example:
img-src 'self' data:;
This allows images from the same origin and data URLs.
Only add sources that your website genuinely requires.
### 4.5 connect-src
The connect-src directive controls browser connections made by scripts, such as fetch, XMLHttpRequest, WebSocket, and EventSource connections.
Example:
connect-src 'self';
If your application communicates with an external API, that API may need to be added to this directive.
### 4.6 font-src
The font-src directive controls the sources from which fonts can be loaded.
Example:
font-src 'self';
If your website uses a trusted external font provider, configure its required origin.
### 4.7 frame-src
The frame-src directive controls which sources can be loaded into nested browsing contexts, such as iframes.
Example:
frame-src 'self';
This can help restrict which external websites your pages are allowed to embed.
### 4.8 object-src
The object-src directive controls sources for plugins and embedded objects.
Example:
object-src 'none';
For many modern websites, disabling these resources is a useful security choice if they are not needed.
### 4.9 base-uri
The base-uri directive restricts which URLs can be used in the HTML base element.
Example:
base-uri 'self';
This helps prevent attackers from changing the base URL used to resolve relative links.
### 4.10 frame-ancestors
The frame-ancestors directive controls which websites are allowed to embed your pages in frames.
Example:
frame-ancestors 'none';
This prevents other sites from embedding the protected page in a frame.
It is an important control for reducing clickjacking risks. Unlike many other CSP directives, frame-ancestors is not supported through a meta element; use an HTTP response header.
## 5. What Is the Difference Between CSP and Other Security Headers?
CSP is one part of a broader website security strategy. Other HTTP security headers protect against different types of threats.
**Content-Security-Policy (CSP):** Controls permitted resource sources and helps reduce the impact of content injection and XSS.
**Strict-Transport-Security (HSTS):** Tells browsers to use HTTPS for future connections to a website for the configured period.
**X-Content-Type-Options:** With the value nosniff, helps prevent browsers from MIME-sniffing certain responses.
**X-Frame-Options:** Provides older browser support for controlling whether a page can be framed. CSP frame-ancestors is the more flexible modern control.
**Referrer-Policy:** Controls how much referrer information browsers send when navigating to other locations.
**Permissions-Policy:** Controls access to certain browser features, such as camera, microphone, and geolocation.
These headers serve different purposes. Adding CSP does not automatically replace the need for other appropriate security headers.
## 6. How to Configure a CSP Header
Before enabling CSP enforcement, website owners should understand how their website loads resources.
A strict policy can break website functionality if it blocks scripts, stylesheets, images, fonts, or API connections that the application needs.
A safer approach is to build and test a policy before enforcing it.
### Step 1: Identify Website Resources
Review your website and identify:
- JavaScript files and their sources.
- CSS files and stylesheets.
- Images and fonts.
- External APIs.
- Analytics and other third-party services.
- Embedded videos or iframe content.
Only include trusted sources that are actually required.
### Step 2: Start With a Report-Only Policy
Content-Security-Policy-Report-Only allows website owners to test a policy without blocking resources.
Example:
Content-Security-Policy-Report-Only: default-src 'self'; object-src 'none'; base-uri 'self';
The browser reports policy violations rather than enforcing the restrictions.
This helps identify resources that would be blocked before switching to enforcement.
### Step 3: Review Violations
Test important website pages and features. Review browser developer tools for CSP violation messages.
Check whether the reported resources are legitimate parts of your application or unexpected content.
Do not automatically trust every reported domain. Confirm that each required source belongs to a service your website intentionally uses.
### Step 4: Configure the Enforced Policy
After testing, publish the policy using the Content-Security-Policy response header.
Start with a policy appropriate for your application. Do not copy a strict configuration from another website without checking compatibility.
### Step 5: Test Again
After enabling enforcement, test your website on desktop and mobile browsers.
Check navigation, forms, login pages, search, images, scripts, APIs, and other important functionality.
If something stops working, investigate the blocked resource and adjust the policy carefully.
## 7. Example: CSP Configuration in Nginx
If your website uses Nginx, you can configure an HTTP response header inside the appropriate server block.
Example:
add_header Content-Security-Policy "default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'" always;
This is a basic illustrative policy, not a universal configuration for every website.
Before using it, confirm that your application does not depend on external scripts, stylesheets, fonts, images, APIs, or embedded content that the policy would block.
The always parameter helps Nginx add the header to responses across different status codes.
After changing the Nginx configuration, test it before reloading:
nginx -t
If the configuration test succeeds, reload Nginx using your normal server administration process.
Always keep a backup of the existing configuration before making production changes.
## 8. What Is CSP Nonce and Why Is It Useful?
A nonce is a unique, unpredictable value generated for a particular response.
A website can use a nonce to allow specific inline scripts while keeping a restrictive script policy.
For example, a policy may contain:
script-src 'nonce-random-value';
The corresponding script element must include the matching nonce attribute.
The nonce must be generated securely and separately for each response. The same predictable value should not be reused across pages or requests.
A nonce-based approach can be useful for websites that need certain inline scripts but want to avoid allowing all inline JavaScript.
Never use a fixed, publicly known nonce as a security measure.
## 9. What Is CSP Hash?
CSP can also use cryptographic hashes to allow specific inline scripts or styles.
A hash is calculated from the exact content of a script or style block. The policy includes the matching hash source.
If the content changes, its hash also changes.
This can be useful for websites with a small number of static inline scripts that do not change frequently.
Nonce and hash approaches are generally safer than broadly allowing inline scripts through unsafe-inline.
## 10. What Is unsafe-inline and unsafe-eval?
Two CSP keywords require particular attention:
**unsafe-inline:** Allows certain inline scripts or styles, depending on the directive. Allowing inline scripts can weaken CSP's protection against XSS.
**unsafe-eval:** Allows JavaScript features that evaluate strings as code, such as eval(). This can increase the impact of certain injection vulnerabilities.
Avoid adding these keywords simply to make browser errors disappear.
If your website needs them, investigate why and consider safer alternatives such as external scripts, nonces, or hashes.
## 11. Common CSP Configuration Mistakes
A poorly configured CSP may provide little protection or may break legitimate website functionality.
Common mistakes include:
### Mistake 1: Using Only default-src
A default-src rule is useful, but it may not provide enough control for a complex application.
Define important directives explicitly according to the website's needs.
### Mistake 2: Allowing Every External Domain
Using broad source permissions can allow resources from untrusted locations.
Allow only the domains that your application genuinely needs.
### Mistake 3: Using unsafe-inline Without Investigation
This can weaken protection against injected inline JavaScript.
Investigate whether nonce or hash-based approaches can solve the problem.
### Mistake 4: Enforcing CSP Without Testing
A restrictive policy can break important website features.
Use Report-Only mode first, review violations, and test the application before enforcement.
### Mistake 5: Forgetting Third-Party Services
Payment systems, analytics, video players, fonts, and external APIs may require specific sources.
Identify these dependencies before enforcing the policy.
### Mistake 6: Treating CSP as Complete Website Security
CSP cannot fix insecure server-side code, weak passwords, broken access control, vulnerable software, or every XSS vulnerability.
It must be combined with secure development and regular security testing.
## 12. How to Check Whether Your Website Has a CSP Header
You can check a website's HTTP response headers using several methods.
### Method 1: Using a Browser
Open your website in Chrome.
Open Developer Tools, select the Network tab, reload the page, and select the main document request.
Look under Response Headers for:
Content-Security-Policy
If the header is present, review its directives and permitted sources.
Also check whether the website uses Content-Security-Policy-Report-Only instead.
### Method 2: Using the curl Command
You can inspect response headers from a terminal using:
curl -I https://example.com
Replace example.com with your own website or a domain you are authorized to test.
Look for the Content-Security-Policy header in the response.
Remember that a header being present does not automatically mean its policy is secure. You must review the actual directives and sources.
### Method 3: Using Cyber Recon Pro
Website security testing can help identify missing or misconfigured HTTP security headers.
To review your website:
1. Open Cyber Recon Pro.
2. Go to the Website Testing feature.
3. Enter a website that you own or have permission to assess.
4. Run the available website security test.
5. Review the security-header findings.
6. Check whether Content-Security-Policy is present.
7. Review the reported configuration and investigate any warnings.
A missing CSP header is a useful security observation, but it should be assessed in the context of the website's architecture and risk.
A present CSP header should also be reviewed for weak directives, overly broad source permissions, and unnecessary exceptions.
## 13. Does Every Website Need CSP?
CSP is useful for many websites, including:
- Business websites.
- E-commerce platforms.
- Online banking applications.
- Content management systems.
- SaaS applications.
- Blogs and publishing platforms.
- Web portals and dashboards.
- Websites with user-generated content.
The exact policy depends on the website's functionality and architecture.
A simple static website may need a relatively straightforward policy. A complex application with multiple APIs and third-party services may need more detailed configuration.
The important point is to create a policy based on actual resource requirements instead of blindly copying a template.
## 14. CSP and Cross-Site Scripting (XSS)
Cross-Site Scripting is a vulnerability in which an attacker can cause malicious JavaScript or other browser-executable content to run in another user's browser.
For example, an application that displays user input without proper output encoding may allow injected content to become executable HTML or JavaScript.
CSP can reduce the impact of some XSS attacks by restricting which scripts the browser is permitted to execute.
However, CSP is not a substitute for fixing the underlying vulnerability.
Developers should still:
- Validate input where appropriate.
- Encode output according to its context.
- Avoid unsafe HTML insertion.
- Use secure templating practices.
- Keep software and dependencies updated.
- Test applications for XSS vulnerabilities.
A strong security approach combines secure coding with browser-level protection.
## 15. How Often Should You Review CSP?
CSP should be reviewed whenever important changes are made to a website.
For example:
- When adding a new JavaScript library.
- When integrating an external API.
- When changing hosting or server configuration.
- When adding a payment provider.
- When redesigning frontend functionality.
- When adding embedded videos or external fonts.
- During regular website security assessments.
Regular review helps prevent outdated rules and unnecessary permissions from remaining in production.
## 16. Frequently Asked Questions (FAQs)
### Q1. What does CSP stand for?
CSP stands for Content Security Policy. It is a browser security standard that controls which sources a webpage is allowed to load resources from.
### Q2. Does CSP prevent all XSS attacks?
No. CSP can reduce the impact of certain XSS attacks, but it does not eliminate every XSS vulnerability. Secure coding and proper output encoding are still necessary.
### Q3. Is Content Security Policy an HTTP security header?
Yes. Content-Security-Policy is commonly delivered as an HTTP response header.
### Q4. What happens if a website does not have CSP?
The browser will not receive that CSP policy from the website. This does not automatically mean the website is vulnerable, but it means that this additional browser-level security control is not being provided through that response.
### Q5. Can CSP break my website?
Yes. An overly restrictive policy may block legitimate scripts, stylesheets, images, fonts, APIs, or embedded content. This is why testing in Report-Only mode is useful.
### Q6. What is the difference between CSP and CSP Report-Only?
Content-Security-Policy enforces the policy and blocks disallowed resources. Content-Security-Policy-Report-Only reports violations without enforcing the restrictions.
### Q7. Is CSP enough to secure a website?
No. CSP is one security layer. A secure website also needs safe application code, updated software, access controls, HTTPS, secure authentication, and regular vulnerability testing.
### Q8. Can I configure CSP using Nginx?
Yes. Nginx can send a Content-Security-Policy HTTP response header using the add_header directive.
### Q9. What is the safest CSP policy?
There is no single policy that is safest for every website. A good policy is restrictive, uses only trusted resource sources, avoids unnecessary unsafe keywords, and is tested against the application's real requirements.
### Q10. How can I test my website's CSP?
You can inspect HTTP response headers through browser Developer Tools, use the curl command, and review your website with a security testing tool.
## Conclusion
Content Security Policy is an important part of modern website security. It gives website owners control over which resources browsers can load and helps reduce the impact of certain content-injection and Cross-Site Scripting attacks.
However, simply adding a CSP header does not guarantee that a website is secure. The policy must be carefully designed, tested, and maintained.
Start by identifying your website's trusted resources, use Report-Only mode to discover violations, and enforce a suitable policy after testing.
Regularly review your HTTP security headers and application behavior to maintain a stronger security posture.
**Improve your website security with Cyber Recon Pro.** Test your website, review available security findings, identify potential weaknesses, and take informed steps toward a safer web application.
Only scan websites and systems that you own or have explicit permission to test.