在 Debian 上搭建 LNMP(Linux + Nginx + MySQL + PHP) 出现 403 Forbidden 是非常常见的问题,通常不是程序代码问题,而是权限或配置问题。下面按最常见原因逐一说明,并给出对应解决办法。
错误表现
403 Forbidden
原因
www-data解决办法
# 假设网站目录是 /var/www/html
chown -R www-data:www-data /var/www/html
chmod -R 755 /var/www/html
原因
index.php / index.htmlautoindex解决方式一:加首页
ls /var/www/html
# 如果没有 index.php,创建一个
解决方式二:允许目录浏览(不推荐生产环境)
location / {
autoindex on;
}
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
Debian 默认 没有 SELinux,但 AppArmor 可能影响 Nginx。
检查:
aa-status
临时测试:
systemctl stop apparmor
原因
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;
}
错误示例
root /var/www;
但实际目录是:
/var/www/html
如:
http://ip/
但:
autoindex on# 查看 nginx 错误日志
tail -n 50 /var/log/nginx/error.log
# 查看网站目录权限
ls -ld /var/www/html
ls -l /var/www/html
# 测试 nginx 配置
nginx -t
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;
}
}
你可以直接贴出:
我可以一步一步帮你精确到哪一行配置导致的 403。