Error 500 - Premature end of script headers
We have been puzzled in the past few days with a rare error that some Magento 2 setups trigger. It is in effect a white screen with underlaying 500 server error:
This error is very very hard to debug and we've been puzzled with this for hours, it's not a PHP error, it doesn't get recorded in error_get_last(), nor in Apache's log files where it just says Error 500: Premature end of script headers: index.php
After lots of debugging, we figured one of the reasons that could be triggering this error and it seems to be related to Content Security Policy headers. If you have huge CSP defined, then the 'Content-Security-Policy' header size can become more than 8KBs where as it is limited to 8KB in nginx and apache2. This is triggering a 500 error and a white screen in Magento 2. A solution would to be to check /etc/csp_whitelist.xml and remove any duplicates, also check any third party extension that could be adding to this security policy and remove any duplicates and unneeded records.
To exclude CSP issue, you can do a quick header size calculation by creating a small Magento 2 plugin.
In vendor\YOUR SPACE\YOUR MODULE\etc\frontend\di.xml, define the following plugin
Once done, create a plugin file e.g. Plugin/Response.php with the following content:
Once done, flush cache and refresh the page. If the CSP headers size is in excess of 8KB, it will throw an error and you shall be able to identify this as a CSP issue. Note that the CSP header itself can be big even if less than 8KB the combined headers size could exceed 8KB so you may alter the code to calculate all header size combined.
Temporary NGINX fix
If you use an NGINX server, you can try to increase the header buffer size from 8KB to 16KB or event 32KB, this is a temporary solution and it will fail again should the header size reach those limits.
1. To apply this fix, on the Nginx HTTP server, open the server configuration file. (configuration path my differ on your system)
2. Add the following configuration line and save config
Temporary fix in APACHE server
To increase the limit, adjust the parameter LimitRequestFieldSize for the virtual host or location in the Apache configuration.
Fixing using a ready module for Magento 2
There is an open source extension for Magento 2 that might help fixing the issue. It is based on splitting the Content-Security-Policy header into chunks. Find more here - https://github.com/basecom/magento2-csp-split-header
Disabling Content Security policy in Magento 2
As a last resort you can disable the CSP entirely