Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

click's avatar
Level 35

Overwrite Nginx Content-Security-Policy within PHP?

Hello,

I'm wondering if it possible to overwrite the Content-Security-Policy configured in an Nginx configuration from within PHP (Laravel).

Currently I'm unable to do so and I can't find anything about it on the web if this is even possible or not.

Nginx config

add_header Content-Security-Policy "default-src 'self'";

PHP

Route::get('wiki', function(){
    return response('<iframe src="https://www.wikipedia.org"></iframe>')->withHeaders([
        'Content-Security-Policy' => 'default-src https://www.wikipedia.org',
    ]);
});

Response

content-security-policy: default-src https://www.wikipedia.org
content-security-policy: default-src 'self'

Result Wikipedia is not loaded in the iframe. If I change the nginx config to: default-src https://www.wikipedia.org wikipedia is loaded into the iframe.

Anyone that has experience with this? Is it even possible to overwrite CSP headers from within PHP if they are already set.

Thanks

0 likes
4 replies
Xsecrets's avatar

If you are a member the latest vue spa video covers this.

Xsecrets's avatar

sorry mixing up all the stupid web security stuff that starts with C. I don't know if you can overwrite headers set my nginx, but my gut instinct would be no you need to change it in the nginx config.

click's avatar
Level 35

@xsecrets it looks like it is impossible but can't find any documentation about it.

What does work (in chrome at least) is when you have a CSP like this in your nginx:

add_header Content-Security-Policy "default-src 'self'";

and you use this in your PHP

Route::get('wiki', function(){
    return response('<iframe src="https://www.wikipedia.org"></iframe>')->withHeaders([
        'Content-Security-Policy' => "frame-ancestors 'self' https://www.wikipedia.org",
    ]);
});

So it looks you can only overwrite "groups" that are not yet set.... but I don't know if this is a solid and future proof solution...

I'm going to remove the nginx setting for now and do it all in my php application.

Please or to participate in this conversation.