HTML
Implement a Robust Content Security Policy (CSP)
Protect your web application from Cross-Site Scripting (XSS) and data injection attacks by defining trusted sources for content using a Content Security Policy.
<!-- Example CSP meta tag for basic protection -->
<meta http-equiv="Content-Security-Policy" content="
default-src 'self';
script-src 'self' https://trusted.cdn.com;
style-src 'self' 'unsafe-inline' https://trusted.cdn.com;
img-src 'self' data: https://cdn.example.com;
font-src 'self' https://fonts.gstatic.com;
frame-ancestors 'none';
form-action 'self';
object-src 'none';
base-uri 'self';
upgrade-insecure-requests;
">
<!-- Or via HTTP Header (e.g., in Nginx config) -->
# add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://trusted.cdn.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; form-action 'self'; frame-ancestors 'none'; object-src 'none'; base-uri 'self'; upgrade-insecure-requests;";
How it works: A Content Security Policy (CSP) is a powerful security mechanism that helps mitigate Cross-Site Scripting (XSS) and other code injection attacks by specifying trusted sources for various types of content (scripts, styles, images, etc.). It instructs the browser to only load resources from explicitly allowed domains, reducing the attack surface. This example demonstrates a policy delivered via a meta tag, restricting scripts and styles to the origin itself and a trusted CDN, preventing all framing, and forcing HTTPS for insecure requests.