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

Nginx+PHP-FPM容器环境下访问根路径返回403问题求助

Nginx+WordPress PHP-FPM环境下403 Forbidden问题解决

问题背景

在Nginx容器搭配WordPress PHP-FPM(端口9000)的环境中,访问HTTPS根路径/时返回403 Forbidden,请求日志如下:

10.0.2.2 - - [09/Sep/2023:18:04:23 +0000] "GET / HTTP/1.1" 403 199 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"

Nginx错误日志提示目录索引被禁止:

2023/09/09 18:04:23 [error] 7#7: *5 directory index of "/var/www/html/" is forbidden, client: 10.0.2.2, server: dcruz-na.42.fr, request: "GET / HTTP/1.1", host: "localhost"

当前使用的Nginx配置:

server {
    server_name dcruz-na.42.fr www.dcruz-na.42.fr;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_certificate /etc/nginx/ssl/dcruz-na.crt;
    ssl_certificate_key /etc/nginx/ssl/dcruz-na.key;
    ssl_ciphers 'TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';

    listen 443 ssl;
    listen [::]:443 ssl;
        

    root /var/www/html;
    
    index index.php;
    
    location / {
        autoindex off;
            try_files $uri $uri/ /index.php?$args;
        }
        
    location ~ [^/]\.php(/|$) {
        fastcgi_index index.php;
            try_files $uri =404;
            fastcgi_pass wordpress:9000;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

需求是让WordPress的PHP-FPM容器处理PHP文件,访问/时返回index.php内容。


解决方案

方法一:简化try_files规则(推荐)

问题出在try_files $uri $uri/ /index.php?$args;中的$uri/——当访问/时,Nginx会先尝试访问目录索引,而autoindex off导致目录索引被禁止,进而触发403。移除$uri/即可让Nginx直接尝试转发到/index.php:

修改location /块为:

location / {
    autoindex off;
    try_files $uri /index.php?$args;
}

这样访问根路径时,Nginx会直接将请求转发给PHP-FPM处理index.php。

方法二:保留目录访问逻辑的替代方案

如果需要支持真实目录的访问(比如存在静态文件目录),可以将PHP处理逻辑抽成命名location,避免目录索引检查冲突:

location / {
    autoindex off;
    index index.php;
    try_files $uri $uri/ @php_handler;
}

location @php_handler {
    fastcgi_pass wordpress:9000;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root/index.php;
    fastcgi_param QUERY_STRING $args;
}

location ~ [^/]\.php(/|$) {
    fastcgi_index index.php;
    try_files $uri =404;
    fastcgi_pass wordpress:9000;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

当$uri和$uri/都无法匹配时,请求会被转发到@php_handler,直接让PHP-FPM处理index.php。


额外检查项

  • 确认Nginx容器的/var/www/html目录已正确挂载WordPress容器的文件目录,确保index.php存在于该路径下。
  • 验证WordPress容器的PHP-FPM服务正常运行,且Nginx容器能够通过wordpress:9000地址访问到该服务。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:43:22