如何在不修改nginx.conf的前提下,通过新增conf的方式来管理多个页面

下图为nginx.conf的配置,希望通过加载conf.d中的*.conf来打开新页面,请求方式为:124.223.1.1/demo1、124.223.1.1/demo2,如果可行demo1和demo2的conf文件该怎么写?

img


下面是我调试时的demo.conf,通过地址124.223.1.1/demo访问得到404

img


img

该回答引用GPTᴼᴾᴱᴺᴬᴵ
1.你可以在nginx.conf中添加一个include语句,用于加载conf.d文件夹中的所有*.conf文件。具体步骤如下:

在http块中添加以下语句:

http {
    ...
    include /etc/nginx/conf.d/*.conf;
    ...
}


这个语句告诉Nginx加载conf.d文件夹中的所有.conf文件。

2.在conf.d文件夹中,为每个页面(如demo1、demo2)创建一个新的*.conf文件,例如:

server {
    listen 80;
    listen [::1]:80;
    server_name 124.223.115.179;
    root /home/www/demo1;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
    }
}


server {
    listen 80;
    listen [::1]:80;
    server_name 124.223.115.179;
    root /home/www/demo2;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
    }
}


这两个文件分别定义了demo1和demo2的配置信息。需要注意的是,每个文件中的server_name应该与之前在nginx.conf中定义的相同。

3.重新启动Nginx服务,使配置生效:

sudo systemctl restart nginx


完成上述步骤后,你应该可以通过124.223.1.1/demo1和124.223.1.1/demo2访问你的两个页面了。

server {
    listen 80;
    server_name 124.223.1.1;
    location /demo1 {
        root /var/www/demo1;
        index index.html;
    }
}
server {
    listen 80;
    server_name 124.223.1.1;
    location /demo2 {
        root /var/www/demo2;
        index index.html;
    }
}

然后在nginx.conf的http块中添加:

include /etc/nginx/conf.d/*.conf;