Recruitment
Viettel IDC

What Is CSP? A Guide to Content Security Policy for Websites

Aug 27, 2026

CSP (Content Security Policy) is a security policy that allows browsers to load content only from trusted sources, helping prevent XSS attacks, block malicious code, and protect website data. Together with Viettel IDC, let’s explore what CSP is, how it works, and why every modern website should implement it.

What Is CSP? A Guide to Content Security Policy for Websites

What Is CSP?

CSP (short for Content-Security-Policy) is a security policy that allows browsers to control the resources a website is permitted to load, thereby preventing XSS attacks and limiting malicious code injection into web pages. CSP works by allowing a website to load scripts, CSS, images, fonts, or iframes only from trusted sources that have been predefined.

A basic Content Security Policy configuration example:

Content-Security-Policy:

  default-src 'self';

  script-src 'self' https://cdn.example.com;

  style-src 'self' https://fonts.googleapis.com;

  font-src https://fonts.gstatic.com;

  img-src 'self' data:;

  connect-src 'self' https://api.example.com;

  frame-ancestors 'none';

Specific explanations:

- default-src 'self': Only loads content from the website itself.

- script-src: Allows JavaScript to run only from the primary domain and trusted CDN.

- style-src: Allows CSS to be loaded from Google Fonts.

- img-src: Allows images from the website and Base64-encoded images.

- connect-src: Allows API requests from authorized sources.

- frame-ancestors: Prevents other websites from embedding your website.

Why Is CSP Important for Web Security?

CSP acts as a proactive layer of protection directly in the browser, helping prevent unsafe content from being loaded and executed. By strictly controlling resource sources, CSP has become an important component in protecting the integrity and security of websites.

- Mitigates XSS attacks: CSP only allows JavaScript to run from defined sources while blocking unsafe inline JavaScript and eval(). As a result, even if an attacker manages to inject a malicious script, the browser will refuse to execute it.

- Protects HTTPS connections: CSP helps reinforce the use of HTTPS, ensuring that data exchanged between clients and servers remains encrypted. When CSP requires resources to be loaded only over HTTPS, websites can more easily enforce secure connections and maintain content integrity.

- Blocks untrusted content: CSP prevents websites from unintentionally loading content such as scripts, images, or iframes from unsafe or unknown sources. This helps prevent improper data collection or information leakage to unwanted third parties. As a result, websites are better protected against malware and external attacks.

How Does CSP Work as a Security Mechanism?

CSP is enforced by the browser based on how a website sends its security policy along with each page. There are two common implementation methods:

CSP via HTTP Header

CSP can be sent to the browser through the Content-Security-Policy HTTP header or through a <meta> tag in HTML. When the browser receives this header, it interprets it as a set of rules (directives) defining which resource sources are permitted.

For example, if the policy declares script-src 'self' example.com, the browser will only allow JavaScript to be loaded from the current website and the example.com domain; all other sources will be blocked.

CSP via the Meta Tag in HTML

You can also configure CSP directly in HTML when you cannot modify the server. This approach is suitable for quick testing or for applying a policy to individual pages. For example, a CSP configuration using an HTML meta tag:

<meta http-equiv="Content-Security-Policy" content="default-src 'self';">

When the browser encounters this tag inside the <head> section, it will only allow resources to be loaded from the current domain and automatically block all content from external sources.

Why Is CSP Important for Web Security?

The Most Important CSP Directives

CSP consists of multiple directives, with each directive controlling a specific type of resource on the website. The table below provides a quick overview of the functions and configuration of the most important CSP directives.

Directive

Function

Configuration Example

default-src

Default source for all resources when no specific directive is defined.

default-src 'self';

script-src

Controls the sources from which JavaScript can be loaded and executed, helping prevent XSS attacks.

script-src 'self' https://cdn.example.com;

style-src

Specifies the sources from which CSS can be loaded.

style-src 'self' 'unsafe-inline';

img-src

Specifies the permitted image sources.

img-src 'self' data:;

font-src

Allows fonts to be loaded from valid domains.

font-src https://fonts.gstatic.com;

connect-src

Specifies sources for AJAX, fetch(), WebSocket, and API connections.

connect-src 'self' https://api.example.com;

frame-ancestors

Determines which websites are allowed to embed your page through an iframe.

frame-ancestors 'self';

form-action

Specifies the domains allowed to receive data from forms.

form-action 'self' https://secure.example.com;

media-src

Specifies sources for audio and video.

media-src media1.com media2.com;

object-src

Specifies sources for plug-ins and content such as PDF and Flash.

object-src 'none';

base-uri

Restricts the value of the <base> tag to prevent changes to link destinations.

base-uri 'self';

How to Implement Content Security Policy

Step 1: Create a CSP Header on the Server

The most complete way to implement CSP is to configure the Content-Security-Policy HTTP header directly on the server. When this header is sent with each response, the browser applies the entire declared security policy and strictly controls which resources are allowed to load.

This method also supports all CSP features and is suitable for systems running on Nginx, Apache, or similar platforms. Example Nginx configuration:

add_header Content-Security-Policy "<policy>";

Step 2: Test CSP in Report-Only Mode

Before officially enforcing CSP, you should enable Content-Security-Policy-Report-Only mode to identify potential violations. In this mode, the browser does not block resources but still logs violations in the console or sends violation reports to an endpoint through report-uri or report-to.

This allows you to identify blocked script, style, image, or API sources without causing display errors or affecting the user experience. Example configuration:

Content-Security-Policy-Report-Only: <policy>;

Step 3: Identify and Add Trusted Resource Sources

After collecting data in Report-Only mode, you need to compile a complete list of the valid domains currently used by the website, including CDNs, third-party APIs, script sources, styles, fonts, and communication components such as WebSockets.

This step is important to ensure that CSP does not incorrectly block legitimate resources when it is officially enabled. For required inline scripts, you should use a nonce or hash instead of allowing unsafe-inline, in order to maintain the highest possible level of security.

Step 4: Finalize the Policy and Deploy CSP

Once the whitelist is complete and there are no remaining critical violations, you can switch to the Content-Security-Policy header to enable full enforcement. This is the strict enforcement state, in which any source not included in the policy is rejected.

Note that the policy should be sent with all responses, not just the homepage, so that the browser applies it consistently across the entire website. Example of official enforcement:

Content-Security-Policy: <policy>;

Step 5: Monitor and Update the CSP Policy

After deployment, you should regularly review reports from report-uri or report-to to identify new violations when the website's interface changes or new third-party services are added. You can also use tools such as CSP Evaluator or browser security testing tools to review and optimize the policy.

Challenges and Solutions When Implementing CSP

Implementing CSP strengthens security, but incorrect configuration can cause display issues or unintentionally block legitimate resources. Below are some common challenges and corresponding solutions to ensure that CSP operates reliably.

- It can break website functionality: A strict CSP may sometimes block legitimate scripts or resources that have not been declared, causing forms, maps, or videos to stop working. You can minimize this issue by running Report-Only mode first and then adding trusted sources to the whitelist based on violation logs.

- Handling dynamic content and inline scripts: Inline or dynamic scripts, such as widgets, chat tools, or counters, may be blocked by CSP if they are not configured correctly. To allow these components to operate securely, you should use nonces or hashes in accordance with CSP Level 3 and explicitly define permitted CDNs in script-src.

- CSP does not replace secure coding practices: CSP cannot prevent XSS vulnerabilities originating from the source code itself, particularly server-side code injection vulnerabilities. Therefore, you still need to maintain security practices such as input validation, output encoding, and adherence to secure coding principles.

- Limited support in older browsers: Some older browsers may not understand or may ignore CSP, meaning the policy may not be fully enforced. The best approach is to identify your target browser group and implement additional protection mechanisms, such as X-Frame-Options, for platforms that do not support CSP.

Conclusion

Through this article, you now have a clear understanding of what CSP is and why Content Security Policy is an important security layer for protecting websites against XSS, blocking malicious code, and controlling all resources loaded by the website. When implemented correctly, CSP becomes an essential part of a modern security strategy, helping ensure that websites operate safely and reliably against threats on the Internet.

For consultation and information about Viettel's services, you can contact Viettel IDC directly through the following channels:

- Hotline: 1800 8088 (toll-free)

- Fanpage: https://www.facebook.com/viettelidc

- Website: https://viettelidc.com.vn

 

Comment ()

Login | Sign Up
to send comment
Your comment will be reviewed before being posted.
Your comment will be reviewed before being posted.
Your comment will be reviewed before being posted.
Read more

Related news

24/09/2026

Kubernetes vs Serverless? Which Is the Right Choice for Enterprise Architecture?

In the Cloud Native era, Kubernetes vs Serverless represents a classic clash between two philosophies: Maximum control or ultimate convenience? If Kubernetes can be considered the solid backbone for complex Microservices systems, Serverless is the speed-driven launchpad that helps optimize costs for enterprises. So, which one is the right fit for your architecture?

24/09/2026

What Is Kubespray? A Production-Ready Kubernetes Deployment Solution for Enterprises

Kubernetes has revolutionized Container orchestration, providing an efficient and flexible solution for application deployment. However, manually setting up and maintaining a Kubernetes Cluster is often highly complex and can easily become overwhelming.

24/09/2026

What Is Minikube? A Beginner’s Guide to Running Kubernetes

Do you want to start learning Kubernetes but are concerned about server rental costs or complicated configuration? Minikube is the perfect answer. So, what is Minikube, and how does this tool turn your laptop into a “pocket-sized” Kubernetes Cluster that you can use for completely free hands-on practice?

24/09/2026

What Is a Helm Chart? The Most Effective Way to Manage Kubernetes Applications

Are you overwhelmed by having to manage dozens of separate YAML configuration files every time you deploy an application to Kubernetes? That’s when you need Helm Chart – a solution often described as the key to escaping configuration hell.

24/09/2026

What Is a Service in Kubernetes? A Complete A-Z Guide to Service Types and Configuration

In the Kubernetes world, Pods have one defining characteristic: they are ephemeral. They are constantly created, terminated, and replaced. Each time this happens, a Pod’s IP address changes. This creates a challenging problem: How can A communicate with B if B’s IP address keeps changing? The answer is Kubernetes Service.

24/09/2026

What Is a Namespace in Kubernetes? A Complete A-Z Guide to Creating and Managing Namespaces

A Kubernetes Cluster is like a huge office building. Without proper zoning, resource conflicts between departments (Dev, Test, Prod) are inevitable. Kubernetes Namespaces are the essential partitions that divide physical infrastructure into multiple Virtual Clusters, ensuring effective isolation and management.

24/09/2026

Kubernetes Cost Optimization: Effective Cloud Cost Reduction Strategies for Businesses

Kubernetes enables businesses to deploy and operate containerized applications at scale with greater flexibility. However, this flexibility also comes with increasingly complex cost management challenges. Kubernetes cost optimization is not simply about cutting resources or shrinking the cluster.

24/09/2026

What Is the Vertical Pod Autoscaler? Effectively Optimizing Pod Resources in Kubernetes

In Kubernetes, manually setting CPU and memory resources for Pods can easily lead to either resource shortages or infrastructure waste. Improper configuration can cause applications to slow down, experience OOMKilled errors, or prevent the cluster from fully utilizing its available capacity. The Vertical Pod Autoscaler provides a smarter approach by automatically recommending and adjusting resources based on actual usage.

24/09/2026

What Is the Kubernetes Scheduler? How Kubernetes Decides Where Pods Run

In Kubernetes, a Pod does not automatically start running immediately after it is created. It first needs to be assigned to a suitable node within the cluster. This task is handled by the Kubernetes Scheduler, whose role is to determine where a Pod should run. The Scheduler helps allocate resources efficiently, maintain system stability, and optimize overall performance.

24/09/2026

Kubernetes vs Docker: Understanding the Key Differences for Effective Container Deployment

During the application containerization process, many people who are new to DevOps often confuse Docker and Kubernetes as two tools with the same role, and some even believe that learning only one of them is sufficient. In reality, Docker and Kubernetes solve two completely different problems, but they are closely connected within modern deployment architectures.