Nginx出现403 Forbidden、404 Not Found错误的解决方案

时间:2025-03-23 10:37:05

一、Docker创建Nginx容器

Docker命令

docker run -d \
  --name nginx \
  -p 80:80 \
  -v /root/nginx/dist:/usr/share/nginx/html \
  -v /root/nginx/:/etc/nginx/ \
  nginx

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       ;
    default_type  application/json;

    sendfile        on;
    
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;

        location / {
            root /root/nginx/dist;
            index ;
        }

        error_page   500 502 503 504  /;
        location = / {
            root /root/nginx/dist;
        }
    }
}

二、403 Forbidden

2.1 问题分析

默认情况下,使用Docker创建的Nginx容器默认会以nginx用户运行,而不是root用户

2.2 解决方案

在Nginx配置文件中,指定Nginx以root用户运行

user root;		# 此配置应添加到Nginx配置文件的开头 
user root;		# 此配置应添加到Nginx配置文件的开头 

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       ;
    default_type  application/json;

    sendfile        on;
    
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;

        location / {
            root /root/nginx/dist;
            index ;
        }

        error_page   500 502 503 504  /;
        location = / {
            root /root/nginx/dist;
        }
    }
}

三、404 Not Found

3.1 问题分析

Nginx配置文件中location /块的root指令,错误地指向了主机上的/root/nginx/dist目录,而不是容器内的/usr/share/nginx/html目录

3.2 解决方案

修改Nginx配置文件中location /块的root指令,确保其指向容器内的/usr/share/nginx/html目录

location / {
    root /usr/share/nginx/html;
    index ;
}

error_page   404 500 502 503 504  /;
location = / {
    root /usr/share/nginx/html;
}
user root;

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       ;
    default_type  application/json;

    sendfile        on;
    
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;

        location / {
            root /usr/share/nginx/html;
            index ;
        }

        error_page   404 500 502 503 504  /;
		location = / {
		    root /usr/share/nginx/html;
		}
    }
}