前言
隨着nginx的使用,一臺服務器下的域名及端口多了以後,在nginx.conf配置文件中就需要不斷的配置server。
久而久之,就會發現nginx.conf特別臃腫。
所以我在這裏對這個nginx.conf進行解耦拆分,讓每個端口都有自己獨立的配置文件。
一、配置nginx.conf 配置文件
簡單講解下:
worker_processes:進程數量
include:檢索路徑下的子配置文件
worker_processes 2;
#日誌
# error_log logs/error.log info;
#記錄pid
pid logs/nginx.pid;
events{
worker_connections 1024;
}
http{
# 開啓GZIP壓縮
gzip on;
# 最小壓縮文件大小
gzip_min_length 4K;
# 壓縮緩衝區
gzip_buffers 4 8K;
# 壓縮等級
gzip_comp_level 2;
gzip_vary on;
# 壓縮類型
gzip_types application/javascript text/css text/plain application/xml font/truetype;
# 開啓高效傳輸模式
sendfile on;
# 隱藏Nginx版本號
server_tokens off;
# 限制最大上傳大小
client_max_body_size 20M;
include mime.types;
default_type application/octet-stream;
include ./config/*.config;
}
二、配置nginx.conf 的子配置文件(子配置下的主端口文件)
1. 新建一個config文件夾,在config文件夾中創建子配置下的主端口文件:nginx_main.config
(名字自定義就行,爲了好區分所以子配置文件的主配置和其他配置文件的區分,我這裏採用了main)
2. 子配置文件中的主配置文件,就是之前默認的 nginx的80端口,我們直接配置路徑就可以了
127.0.0.1,這裏可以把ip修改成自己的域名,例如:www.baidu.com
3. 測試:在瀏覽器中輸入www.baidu.com,默認找到ngixn下的index.html。即:www.baidu.com/index.html
server{
listen 80;
server_name 127.0.0.1;
location ~^/ {
root html;
index index.html index.htm;
}
}
或者 有域名需求的話,可以用這個
server{
listen 80;
server_name www.baidu.com;
location ~^/ {
root html;
index index.html index.htm;
}
}
三、配置nginx.conf 的子配置文件(除主文件配置的以外,子配置下的其他配置端口文件)
1. 在config文件夾中創建子配置下的主端口文件:nginx_map.config
(名字自定義就行,爲了好區分每個子配置文件所對應的域名及端口,儘量名字規則點)
2.由於需要配置多個域名,所以我這裏引入了二級域名:map.baidu.com
3.nginx的主端口80被佔用了,所以需要使用別的端口,那就得需要用到ngixn代理轉發 proxy_pass。
我這裏轉發到8001端口:proxy_pass http://127.0.0.1:8001;
4. 測試:在瀏覽器中輸入map.baidu.com,默認找到ngixn下的index.html。即:map.baidu.com/index.html
server{
listen 80;
server_name map.baidu.com;
location ~^/ {
proxy_pass http://127.0.0.1:8001;
}
}