温馨提示×

debian lnmp为何报403错误

小樊
42
2026-09-10 18:45:37
栏目: 智能运维

在 Debian 上搭建 LNMP(Linux + Nginx + MySQL + PHP) 出现 403 Forbidden 是非常常见的问题,通常不是程序代码问题,而是权限或配置问题。下面按最常见原因逐一说明,并给出对应解决办法。


一、最常见原因汇总(按出现概率)

1️⃣ Nginx 没有权限访问网站目录

错误表现

403 Forbidden

原因

  • 网站目录属主不是 www-data
  • 目录权限过低(如 700)

解决办法

# 假设网站目录是 /var/www/html
chown -R www-data:www-data /var/www/html
chmod -R 755 /var/www/html

2️⃣ 目录中没有 index 文件(且没有自动索引)

原因

  • 目录里没有 index.php / index.html
  • Nginx 未开启 autoindex

解决方式一:加首页

ls /var/www/html
# 如果没有 index.php,创建一个

解决方式二:允许目录浏览(不推荐生产环境)

location / {
    autoindex on;
}

3️⃣ Nginx 的 index 指令配置错误

典型错误配置

location / {
    root /var/www/html;
}

正确示例

server {
    listen 80;
    server_name example.com;

    root /var/www/html;
    index index.php index.html index.htm;

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

修改后:

nginx -t
systemctl reload nginx

4️⃣ SELinux / AppArmor 限制(Debian 少见但有可能)

Debian 默认 没有 SELinux,但 AppArmor 可能影响 Nginx。

检查:

aa-status

临时测试:

systemctl stop apparmor

5️⃣ PHP 未正确解析(访问 .php 报 403)

原因

  • php-fpm 没运行
  • fastcgi 配置错误

检查 PHP-FPM:

systemctl status php-fpm
# 或
systemctl status php8.2-fpm

Nginx 中应有类似:

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php8.2-fpm.sock;
}

6️⃣ Nginx 配置中 root 写错

错误示例

root /var/www;

但实际目录是:

/var/www/html

7️⃣ 访问的是目录但被禁止

如:

http://ip/

但:

  • 没有 index 文件
  • 没有 autoindex on

二、快速排查命令(强烈推荐)

# 查看 nginx 错误日志
tail -n 50 /var/log/nginx/error.log

# 查看网站目录权限
ls -ld /var/www/html
ls -l /var/www/html

# 测试 nginx 配置
nginx -t

三、一个“标准 LNMP 网站配置示例”

server {
    listen 80;
    server_name localhost;

    root /var/www/html;
    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;
    }
}

四、如果你愿意,我可以更精准定位

你可以直接贴出:

  1. Nginx 配置(server 段)
  2. 网站目录结构
  3. error.log 报错内容

我可以一步一步帮你精确到哪一行配置导致的 403。

0