系统环境
Ubuntu 16.04
安装 apache2
sudo apt update # 更新一下软件列表,否则部分软件包获取失败
sudo apt install apache2
使能 CGI
cd /etc/apache2/mods-enabled
sudo ln -s ../mods-available/cgi.load cgi.load
重启
使能 CGI 后,必须重启 apache2
sudo apache2ctl restart
编写脚本
cd /usr/lib/cgi-bin # 默认的存储位置
sudo touch test
sudo chmod +x test # 必须要有可执行权限
sudo mousepad test # 用你喜爱的编辑器打开编写内容
测试脚本
分割行不要漏了。
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
print # 此处一定要输出一个空行,使用这行空行分割额外的响应头和内容
print "Yes, it's work"
浏览器打开
看到 Yes, it's work
证明一切都 OK 了。
firefox http://localhost/cgi-bin/test
更全面的测试脚本
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
print "Content-type:text/html" # 额外的响应头
print # 响应头和内容分割行
print '<html>' # 以下是页面内容
print '<head>'
print '<title>Hello</title>'
print '</head>'
print '<body>'
print '<h2>Hello Word! This is my first CGI program</h2>'
print '</body>'
print '</html>'
查看日志文件
碰到预期外的事情?看看日志文件怎么说。
tail -n 20 /var/log/apache2/error.log # 查看最后 20 条错误记录
tail -n 20 /var/log/apache2/access.log # 查看最后 20 条访问记录