nginx配置文件分解为多个子配置
在nginx配置时,如果需要配置的项目过多,全部配置信息都写在nginx.conf的话,会使得nginx.conf文件过于臃肿,可读性和可维护性差。咱们可以将一个项目为单位,为每个项目配置nginx的子配置文件,这样方便管理。下面介绍下实现的步骤:
1.在nginx.conf的http模块,server节点上方,添加inclue部分的内容,红色加粗部分
http {
# 其他部分,略
keepalive_timeout 65;#gzip on;
#须替换为自己实际的conf.d地址
include /etc/nginx/conf.d/*.conf;
upstream server1{
server 192.157.228.112:8080;
}
# HTTPS server
#
server {
# 服务配置内容,略
}
}
2.在上面的 /etc/nginx/conf.d目录下新建子配置文件,如server1.conf
文件上写上项目的server节点,参考如下:
server {
listen 80;
server_name abc.test.com;
location / {
root /usr/share/nginx/html/dist;
index index.html;
try_files $uri $uri/ /index.html;
}
location /resource/image/ {
root /mnt/files/imFilePath;
try_files $uri $uri/ =404;
}
location /app/ {
proxy_pass http://server1;
proxy_set_header Host $host;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET,POST,DELETE';
add_header 'Access-Control-Allow-Header' 'Content-Type,*';}
location /admin/ {
proxy_pass http://server1;
proxy_set_header Host $HOST;
}
location /logout {
proxy_pass http://server1/logout;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# try_files $uri $uri/ =404;}
location /common/ {
proxy_pass http://server1;
proxy_set_header Host $HOST;
}
}
其中 server1为nginx.conf中配置的对应upstream名称。
这里说下location中的配置:
location / {
root /usr/share/nginx/html/dist;
index index.html;
try_files $uri $uri/ /index.html;
}
root表示:会将 URL 路径直接附加到指定的根目录路径后,
alias
指令用于将 URL 路径映射到文件系统的特定路径。