【问题标题】:500 internal Server error when configuring python cgi配置 python cgi 时出现 500 内部服务器错误
【发布时间】:2020-12-19 09:19:34
【问题描述】:

我一直在尝试使用 CGI 运行一个简单的 python 脚本hello.py,但出现 500 内部服务器错误。

我的python代码。

#!/usr/bin/python2.7
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>'

我运行python脚本的目录在/var/www/crunchworld。我启用的conf文件在`/etc/apache2/conf-available/crunchworld.conf

conf文件的样子

&lt;Directory /var/www/crunchworld&gt;

Options +ExecCGI

AddHandler cgi-script .cgi

Options All

AllowOverride All

Order allow,deny

Allow from all

&lt;/Directory&gt;

我启用了 cgi 并为文件 hello.py 授予了必要的权限,但它仍然显示内部服务器错误。当我检查日志时,我看到了

头文件前的脚本输出结束:hello.py

我已经研究了错误并为该文件提供了适当的权限,但它不起作用。

任何帮助将不胜感激。提前致谢。

我做了进一步的改变

  1. 我在 crunchworld.conf 文件中添加了AddHandler cgi-script .cgi .py

2.我已经给了hello.py文件的权限

  1. 我已将/etc/apache2/conf-available/crunchworld.conf 符号链接到/etc/apache2/conf-enabled

4.我已经在/usr/bin/python2.7 路径上安装了python2.7,我也尝试过使用#!/usr/bin/env python,但还是不行。

查看日志后发现End of script output before headers: hello.py, referer: http://localhost/

感谢您的建议,但它仍然显示 500 内部错误。

【问题讨论】:

    标签: python apache cgi


    【解决方案1】:

    您的 CGI 脚本还必须输出标头信息。

    最低要求是Content-type 标头——在这种情况下应设置为text/html

    将此添加到您的 CGI 脚本的 start 中(在打印其他任何内容之前)。

    print 'Content-type: text/html\n'
    

    注意额外的尾随换行符——必须在标题和内容本身之间至少留一个空行。

    更新:

    要进一步排除故障,请执行以下操作:

    1. 确保您的 CGI 脚本具有正确的权限集:chmod 0755 hello.py 以确保。
    2. 您的脚本似乎是.py,而您的apache 配置似乎只指定.cgi 文件。你的AddHandler 应该是AddHandler cgi-script .cgi .py
    3. 如果您还没有这样做,您应该在/etc/apache2/conf-enabled 中符号链接您的/etc/apache2/conf-available/crunchworld.conf 文件。运行以下命令:cd /etc/apache2/conf-enabled; sudo ln -s ../conf-available/crunchworld.conf
    4. 如果您对 apache 配置进行任何更改,请务必重新启动 apache:例如sudo service apache2 restart
    5. 检查您的 hashbang 行是否正确。 /usr/bin/python2.7 存在吗?您可以尝试改为设置为#!/usr/bin/env python#!/usr/bin/env python2。 (或者更好的是,如果可能在您的系统上切换到 python3)。
    6. 再次检查 apache 错误日志。例如。 tail -20 /var/log/apache2/error.log(或您的日志所在的任何位置)。
    7. 您可以尝试使用cgitb 模块进行进一步调试(请参阅https://docs.python.org/3/library/cgitb.html)。

    【讨论】:

    • 我已经添加了它,但它并没有解决问题..仍然显示内部服务器错误!
    • @avinash-babu 我在我的答案中添加了一些进一步的调试步骤,这可能会对您有所帮助。如果您的问题仍然存在,请edit您的问题,详细说明您执行的步骤,以及您发现的确切日志信息或错误。祝你好运!
    • 感谢您到目前为止的帮助。但它仍然显示来自 localhost 的相同错误..我已经按照您所说的编辑了我的问题..
    • 直接在命令行上运行是否有效:./hello.py?另外,ls -ld . hello.py 显示什么?
    • -rwxr-xr-x 1 avinash avinash 264 Dec 20 13:35 hello.py(ls -ld hello.py 的结果)
    猜你喜欢
    • 1970-01-01
    • 2011-10-09
    • 2016-04-24
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    • 2016-09-05
    相关资源
    最近更新 更多