W3docs

Error 500: Premature end of script headers

Error 500 "Premature end of script headers" is a general error message indicating that there is a problem with the server-side script that is preventing it from executing properly.

Error 500 "Premature end of script headers" is a general error message indicating that there is a problem with the server-side script that is preventing it from executing properly. This could be caused by a variety of issues, such as a syntax error in the script, a problem with the server's configuration, or a lack of permissions to execute the script. To troubleshoot this issue, check the server's error logs for more information and ensure that the script and its dependencies are properly configured and have the necessary permissions.

Common Causes

  • Missing or incorrect shebang line: CGI scripts require a valid shebang (e.g., #!/usr/bin/php) as the absolute first line to tell the server which interpreter to use.
  • PHP syntax errors: A missing semicolon, unclosed bracket, or invalid function call will cause the script to crash before outputting HTTP headers.
  • Incorrect file permissions: The web server user (e.g., www-data or apache) must have execute permissions on the script and read permissions on any included files.

Troubleshooting Steps

  1. Check server error logs: Look for specific PHP warnings or fatal errors that triggered the crash.
    tail -n 50 /var/log/apache2/error.log
    # or for Nginx:
    tail -n 50 /var/log/nginx/error.log
  2. Validate PHP syntax locally: Run the script through the PHP linter to catch syntax errors before deploying.
    php -l /path/to/your/script.php
  3. Verify file permissions: Ensure the script is executable by the web server.
    chmod 755 /path/to/your/script.php
    chown www-data:www-data /path/to/your/script.php

Minimal Working Example

A correctly configured PHP CGI script should include a shebang, valid syntax, and proper permissions:

#!/usr/bin/php
<?php
header('Content-Type: text/html');
echo "Hello, World!";
?>

Save this as index.php, set permissions with chmod 755 index.php, and ensure your web server is configured to execute PHP files via CGI/FastCGI.