Nginx 中 include 指令使用

1、应用场景:

当存在多个域名时,如果所有配置都写在 nginx.conf 主配置文件中,难免会显得杂乱与臃肿。

为了方便配置文件的维护,所以需要进行拆分配置。

2、在 nginx 的 conf 目录下 创建 vhost 文件夹:

[root@Centos conf]# pwd
/usr/local/nginx/conf
[root@Centos conf]# mkdir vhost

3、在 vhost 文件夹中创建 test1.com.conf 和 test2.com.conf 文件:

(1)test1.com.conf 文件内容:

server {
        listen 8000;
        server_name test1.com;
        location / {
            proxy_set_header Host $host:$server_port;
            proxy_set_header X-Real-Ip $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            # proxy_pass http://xxx.xxx.xxx;
            echo "test1.com";    # 输出测试

        }

}

(2)test2.com.conf 文件内容:

server {
        listen 8000;
        server_name test2.com;
        location / {
            proxy_set_header Host $host:$server_port;
            proxy_set_header X-Real-Ip $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            # proxy_pass http://xxx.xxx.xxx;
            echo "test2.com";    # 输出测试

        }

}

4、在 nginx.conf 主配置文件 http{...} 段中加入以下内容:

include vhost/*.conf;    # include 指令用于包含拆分的配置文件

5、编辑 /etc/hosts 文件

# vim /etc/hosts
127.0.0.1 test1.com
127.0.0.1 test2.com

6、测试:

[root@Centos conf]# curl http://test1.com:8000
test1.com
[root@Centos conf]# curl http://test2.com:8000
test2.com
[root@Centos conf]# 

 

posted @ 2020-03-13 18:17  d0usr  阅读(29875)  评论(0编辑  收藏  举报