Python+Apache+CGI完全配置
首先中开社linux系统已经默认安装python,查看方式进入ls /usr/bin/python* -l
所以搭建简单的web服务只需要安装Apache+cgi配置既可使用
安装apache方法如下:
yum install httpd*
安装成功后,开启服务httpd服务
#systemctl enable httpd.service
#systemctl start httpd.service
然后打开http配置文件进行配置进行配置
路径:/etc/httpd/conf/httpd.conf
#vi /etc/httpd/conf/httpd.conf
修改内容如下:
ScriptAlias /cgi-bin/
/var/www/cgi-bin/
可以看到apache将"/var/www/cgi-bin/
"映射为/cgi-bin/,即当你通过浏览器访问/cgi-bin/目录时,实际上就是访问"/var/www/cgi-bin/
"目录,为了方便,我将其设置为如下:
1
|
ScriptAlias
/cgi-bin/
|
设置cgi路径的访问权限
大概在httpd.conf195行:
1
2
3
4
|
<Directory />
AllowOverride none
Require all denied
<
/Directory
>
|
将上面的内容全部修改为下面的内容:
1
2
3
4
5
6
|
<Directory
"
>
AllowOverride None
Options +ExecCGI
Order allow,deny
Allow from all
<
/Directory
>
|
注意这里的目录是修改为前面我们改的:/var/www/cgi-bin/
设置apache可解释python的cgi脚本文件
大概在httpd.conf的386行:
1
|
#AddHandler cgi-script .cgi
|
去掉注释,将其修改为:
1
|
AddHandler cgi-script .cgi .py
|
3.添加CGI脚本文件
(1)创建cgi脚本文件
在/home/xpleaf/Source_Code/cgi_for_py/目录下添加下面一个文件,并命名为hello.py:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#!/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>'
|
注意#!/usr/bin/env python一定要加上,否则会出现500错误提示。
(2)设置cgi脚本文件的文件权限为755
1
2
3
|
xpleaf@leaf:~
/Source_Code/cgi_for_py
$
chmod
755 hello.py
xpleaf@leaf:~
/Source_Code/cgi_for_py
$
ls
-l hello.py
-rwxr-xr-x 1 xpleaf xpleaf 289 1月 31 16:02 hello.py
|
此步非常非常重要,如果忘记这步,无论你怎么找配置文件也找不出错误,就算看代码也不会发现有错误,然后通过浏览器访问时会一直显示500错误,所以一定要记得该步操作!
4.通过浏览器访问cgi脚本文件
直接在浏览器中输入localhost/cgi-bin/hello.py或127.0.0.1/cgi-bin/hello.py就可以访问我们的cgi脚本文件了:
参考链接:http://blog.51cto.com/xpleaf/1740221