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]# 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM