Docker部署WordPress时固定链接触发index.php下载问题排查
首次尝试使用Docker搭配docker-compose部署WordPress,遇到如下问题:当使用http://localhost/wordpress/sample-post这类固定链接结构而非http://localhost/wordpress/?p=123时,访问页面链接会触发下载根目录的index.php文件(并非/wordpress/目录下的文件);即使将WordPress部署在根目录,问题依旧。已参考大量同类问题且自认为配置正确,求可能的原因。
配置文件详情
compose.yaml
services: nginx: image: nginx:latest ports: - 80:80 volumes: - ./nginx.conf:/etc/nginx/conf.d/default.conf - C:/dev:/var/www/html php: build: context: . dockerfile: php.Dockerfile volumes: - ./php.ini:/usr/local/etc/php/conf.d/php.ini - C:/dev:/var/www/html mysql: image: mysql:latest command: --default-authentication-plugin=mysql_native_password environment: - MYSQL_ROOT_PASSWORD=root ports: - 3306:3306
nginx.conf
server { listen 80; server_name localhost; root /var/www/html; error_log /var/log/nginx/error.log; access_log /var/log/nginx/access.log; index index.php index.html index.htm; autoindex on; # to enable directory listing location / { try_files $uri $uri/ /index.php$is_args$args =404; } location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_param HTTP_PROXY ""; # Mitigate https://httpoxy.org/ vulnerabilities fastcgi_pass php:9000; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; } }
php.Dockerfile
FROM php:fpm RUN docker-php-ext-install mysqli pdo pdo_mysql
php.ini
date.timezone=Europe/London max_execution_time=120 upload_max_filesize=40M post_max_size=40M error_reporting=E_ALL & ~E_DEPRECATED & ~E_STRICT
可能的原因及排查方向
Nginx缺失MIME类型配置:当前nginx.conf里没有引入
mime.types文件,Nginx无法识别.php文件的正确MIME类型,会直接将其作为普通文件返回,导致浏览器触发下载。解决方法是在server块开头添加:include /etc/nginx/mime.types; default_type application/octet-stream;try_files规则适配问题:如果WordPress部署在子目录
/wordpress/,当前根路径的try_files会将请求转发到根目录的index.php,而非子目录下的文件。需要针对子目录单独配置location规则:location /wordpress/ { try_files $uri $uri/ /wordpress/index.php$is_args$args; }即使部署在根目录,也要确保
try_files转发的/index.php请求能被PHP处理规则正确捕获。PHP PATH_INFO解析异常:检查
fastcgi_split_path_info规则是否正确拆分路径。当请求通过try_files转发到index.php时,PATH_INFO需要包含原始的固定链接路径,确保WordPress能正确解析路由。可以查看PHP错误日志确认PATH_INFO是否正确传递。文件权限不匹配:Docker中Nginx和PHP-FPM默认以
www-data用户运行,需确保挂载的C:/dev目录下的WordPress文件对www-data有读取权限。可以进入Nginx容器执行ls -l /var/www/html查看权限,必要时在容器内调整权限。WordPress固定链接配置未同步:进入WordPress后台重新保存固定链接设置,这会更新WordPress内部的路由规则。同时检查后台「设置-常规」里的「站点地址(URL)」和「WordPress地址(URL)」是否与实际部署路径一致。
内容的提问来源于stack exchange,提问作者coldpumpkin

