You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apache环境下CGI脚本重定向异常:跳转页面显示代码

问题分析与解决方案

看起来你遇到的核心问题是:CGI脚本在跳转到next_page.html时,浏览器直接显示了该HTML文件的代码而非正常渲染页面,但跳转至login_or_signup.html却一切正常。结合你的代码和现象,我整理了几个关键原因和修复步骤:

1. 检查next_page.html的文件权限

最常见的原因是Web服务器(比如Apache)的运行用户没有读取next_page.html的权限,导致服务器无法正确解析返回文件,只能直接输出源码。

  • 执行以下命令修正权限:
    # 设置文件可读权限
    chmod 644 /var/www/html/next_page.html
    # 将文件归属设置为Web服务器用户(以www-data为例)
    chown www-data:www-data /var/www/html/next_page.html
    

2. 修复CGI重定向的HTTP头格式

你的重定向代码存在两个格式错误,这会导致浏览器无法正确识别重定向指令:

  • Location头前有多余的空格,HTTP头不允许有前导空格
  • 重定向应先发送状态码,再发送Location头,且头与响应体之间必须有一个空行

修改go_back_top和go_forwards_top函数如下:

def go_back_top(data):
    redirectURL = "/login_or_signup.html"
    try:
        # 发送标准的302重定向头
        print "Status: 302 Found"
        print "Location: %s" % redirectURL
        print "Content-type: text/html\n"  # 空行分隔HTTP头和响应体
        # 修正DOCTYPE和引号规范
        print """<!DOCTYPE html>
 <html lang="en">
 <head>
 <meta charset="utf-8"/>
 <meta http-equiv='refresh' content='0;url=%s' />
 <title>Login</title>
 </head>
 <body>
 Redirecting... <a href="%s">Click here if you are not redirected</a>
 </body>
 </html>""" % (redirectURL, redirectURL)
    except:
        cgi.print_exception()
        print "An error occurred\n"
        print"<PRE>"
        cgitb.print_exc()

def go_forwards_top(data):
    redirectURL = "/next_page.html"  # 恢复正确的跳转目标
    try:
        print "Status: 302 Found"
        print "Location: %s" % redirectURL
        print "Content-type: text/html\n"
        print """<!DOCTYPE html>
 <html lang="en">
 <head>
 <meta charset="utf-8"/>
 <meta http-equiv='refresh' content='0;url=%s' />
 <title>Login</title>
 </head>
 <body>
 Redirecting... <a href="%s">Click here if you are not redirected</a>
 </body>
 </html>""" % (redirectURL, redirectURL)
    except:
        cgi.print_exception()
        print "An error occurred\n"
        print"<PRE>"
        cgitb.print_exc()

另外注意:你代码里的<DOCTYPE html>缺少感叹号,正确写法是<!DOCTYPE html>,这个小错误可能导致浏览器解析异常,已经在上面的代码中修正。

3. 验证Web服务器对HTML文件的处理配置

确保你的Web服务器正确识别.html文件为文本/html类型,比如Apache默认会配置AddType text/html .html,如果之前修改过服务器配置,可检查该配置项是否存在。

同时确认next_page.html确实放在了服务器根目录(/var/www/html/)下,和login_or_signup.html同路径,因为你的重定向URL是/next_page.html,对应服务器根目录。

额外建议:修复SQL注入漏洞

你的check_person函数中,SQL语句通过字符串拼接生成,存在严重的SQL注入风险:

sql_str = "SELECT * FROM people WHERE username = '%s'" % (username)

改为参数化查询可彻底避免这个问题:

sql_str = "SELECT * FROM people WHERE username = %s"
cursor.execute(sql_str, (username,))

内容的提问来源于stack exchange,提问作者marienbad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:51:51