The Content-Security-Policy (CSP) header helps protect your website from attacks like cross-site scripting (XSS) by specifying which sources of content are allowed to be loaded on your site. It provides fine-grained control over resources such as scripts, styles, images, and more.
.htaccess file if you use one).Header set Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self';"/etc/nginx/sites-available/your-site).server block, replacing the policy with one tailored to your needs: add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self';";sudo systemctl restart nginxheader("Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self';"); Use a middleware like helmet to set the header automatically:
const helmet = require('helmet');
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'"]
}
})); Or set it manually:
app.use((req, res, next) => {
res.setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self';");
next();
}); from flask import Flask, Response
app = Flask(__name__)
@app.after_request
def set_headers(response):
response.headers['Content-Security-Policy'] = "default-src 'self'; script-src 'self'; style-src 'self';"
return response After setting the header, test your website to ensure itโs working:
Content-Security-Policy header with the correct value.Setting this header helps prevent malicious scripts or resources from being loaded on your website, significantly reducing the risk of attacks like XSS and ensuring a safer browsing experience for your users.