配置Python CGI时遭遇500 Internal Server Error求助
That "End of script output before headers" error is a classic CGI gotcha—Apache expects your script to send HTTP response headers before any HTML content, and right now your Python script is skipping that critical step. Let's walk through the fixes step by step.
Core Issue: Missing HTTP Headers
CGI requires you to first output a Content-Type header followed by two newlines to separate the headers from the actual HTML content. Without this, Apache doesn't recognize the output as a valid HTTP response, hence the 500 error.
Modified Working Script
Update your hello.py to include the required header at the very top (right after the shebang line):
#!/usr/bin/python2.7 # Critical: Send HTTP header first print "Content-type: text/html\r\n\r\n" print '<html>' print '<head>' print '<title>Hello World - First CGI Program</title>' print '</head>' print '<body>' print '<h2>Hello World! This is my first CGI program</h2>' print '</body>' print '</html>'
Verify Other Critical Settings
You've already made some good adjustments, but let's double-check a few more things:
Fix Apache 2.4+ Authorization Syntax
If you're running Apache 2.4 or newer, the oldOrder allow,denyandAllow from alldirectives are deprecated. Update yourcrunchworld.confto use the modern authorization syntax:<Directory /var/www/crunchworld> Options +ExecCGI AddHandler cgi-script .cgi .py AllowOverride All Require all granted </Directory>Note:
Options Allis redundant here since+ExecCGIis already enabled, and it can sometimes override specific settings—better to stick to explicit options.Confirm Script Permissions
Ensure the script is executable and readable by Apache's user (usuallywww-data):chmod +x /var/www/crunchworld/hello.py chown www-data:www-data /var/www/crunchworld/hello.pyRestart Apache to Apply Changes
Don't forget to restart Apache so all configuration and script changes take effect:sudo systemctl restart apache2 # Or for older systems: sudo service apache2 restartValidate Shebang Line
Double-check that/usr/bin/python2.7exists (you mentioned it's installed, but a quick check won't hurt):ls -l /usr/bin/python2.7If you prefer using
env, update the shebang to#!/usr/bin/env python2(make surepython2is in Apache's PATH).
Troubleshooting If It Still Fails
If you still see errors, check Apache's detailed error logs for more clues:
tail -f /var/log/apache2/error.log
Look for additional errors like Python syntax issues, permission denials, or configuration missteps that might be hiding behind the initial header error.
内容的提问来源于stack exchange,提问作者Avinash Babu

