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

Ubuntu 21.04下Apache2配置index.py为首页不执行脚本问题咨询

1. 补全Dockerfile缺失的依赖和配置指令

你使用的Ubuntu Apache基础镜像默认没有安装Python,也没有启用CGI模块,需要在Dockerfile中新增对应指令,同时优化权限配置:

FROM ubuntu/apache2:2.4-21.04_beta

# 安装Python3依赖
RUN apt update && apt install -y --no-install-recommends python3 && \
    rm -rf /var/lib/apt/lists/*

# 启用Apache CGI模块
RUN a2enmod cgi

RUN rm -rf /var/www/html/*
COPY html /var/www/html
# 明确赋予index.py执行权限,避免通配符匹配异常
RUN chmod 755 /var/www/html/index.py
COPY virtual-hosts.conf /etc/apache2/sites-available/000-default.conf

注意:你的index.py文件第一行必须添加shebang声明#!/usr/bin/env python3,否则Apache无法识别脚本解释器

2. 修正virtual-hosts.conf配置

需要新增index.py为默认首页,同时替换Apache 2.4兼容的访问控制规则,修正后的配置如下:

<VirtualHost *:80>
    ServerName pilights

    DocumentRoot /var/www/html
    # 新增配置:将index.py设为默认首页
    DirectoryIndex index.py index.html

    LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    AddHandler cgi-script .py

    <Directory "/var/www/html">
        Options Indexes MultiViews FollowSymLinks ExecCGI
        AllowOverride All
        # 替换旧版访问控制规则,适配Apache 2.4
        Require all granted
    </Directory>
</VirtualHost>

原配置失效的核心原因

  • Ubuntu下的Apache模块统一使用a2enmod/a2dismod工具管理,不需要手动修改apache2.conf添加LoadModule规则,手动添加的模块路径与OSX平台不一致,所以不会生效
  • 未配置DirectoryIndex规则时,Apache默认不会将index.py识别为站点首页,因此访问根路径会返回目录列表
  • 基础镜像默认没有安装Python运行环境,就算权限配置正确,脚本也无法执行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 03:54:03