Nginx未自动加载index.php为默认页面的问题求助
问题描述
基于Nginx创建运行PHP代码的Docker镜像,功能基本正常,但访问根URL(如http://myserver.com)时必须携带index.php才能正常访问PHP内容;省略index.php时,Nginx仅返回默认欢迎页,不会自动加载index.php。
现有配置
Dockerfile
FROM alpine:3.16.2 RUN apk update && apk upgrade RUN apk add --no-cache \ bash \ php8 \ php8-fpm \ php8-json \ php8-mbstring \ php8-mysqlnd \ php8-pdo \ php8-pdo_mysql \ php8-pdo_pgsql \ php8-pdo_sqlite \ libmcrypt-dev \ libltdl RUN apk add openssl curl ca-certificates RUN printf "%s%s%s\n" \ "http://nginx.org/packages/alpine/v" \ `egrep -o '^[0-9]+\.[0-9]+' /etc/alpine-release` \ "/main" \ | tee -a /etc/apk/repositories RUN curl -o /tmp/nginx_signing.rsa.pub https://nginx.org/keys/nginx_signing.rsa.pub RUN openssl rsa -pubin -in /tmp/nginx_signing.rsa.pub -text -noout RUN mv /tmp/nginx_signing.rsa.pub /etc/apk/keys/ RUN apk add nginx COPY ./default.conf /etc/nginx/conf.d/default.conf COPY ./index.php /usr/share/nginx/html/ EXPOSE 80 EXPOSE 443 STOPSIGNAL SIGTERM CMD ["/bin/bash", "-c", "php-fpm8 && chmod 755 /usr/share/nginx/html/* && nginx -g 'daemon off;'"]
Nginx默认配置(default.conf)
server { listen *:80; index index.php index.html; server_name myserver; error_log /var/log/nginx/error.log; access_log /var/log/nginx/access.log; root /usr/share/nginx/html; location / { try_files $uri $uri/ /index.php?$query_string; # gzip_static on; } location ~ \.php$ { try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; } }
解决方案
问题核心是Nginx安装后自带的index.html文件优先级高于你的index.php,虽然配置里index指令把index.php放在前面,但只要index.html存在,Nginx就会优先返回它。需要做以下修改:
1. 修改Dockerfile,删除默认index.html
在COPY ./index.php /usr/share/nginx/html/之后添加一行,删除Nginx默认的欢迎页:
RUN rm /usr/share/nginx/html/index.html
修改后的Dockerfile相关片段:
COPY ./index.php /usr/share/nginx/html/ RUN rm /usr/share/nginx/html/index.html EXPOSE 80 EXPOSE 443
2. 验证现有Nginx配置(无需修改)
你的default.conf已经配置了正确的自动索引和路由规则:
index index.php index.html;确保PHP索引文件优先级更高location /里的try_files $uri $uri/ /index.php?$query_string;确保当请求路径不存在时,转发到index.php处理
这部分配置无需调整,只要删除默认的index.html,就能触发自动加载index.php。
3. 重新构建并测试
执行以下命令重新构建镜像并运行:
docker build -t php-nginx . docker run -p 80:80 php-nginx
访问http://localhost即可自动加载index.php内容。
内容的提问来源于stack exchange,提问作者FernSeher
相关产品推荐
相关产品推荐

