「Nginx」- 配置文件语法 | 格式化工具 | 学习笔记

配置文件结构

简单示例:

user www-data;
worker_processes auto;
worker_cpu_affinity auto;
pid /run/nginx.pid;
error_log /var/log/nginx/error.log;
include /etc/nginx/modules-enabled/*.conf;

events {
	worker_connections 768;
	# multi_accept on;
}

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

mail {
	server { }
	server { }
}

使用 if 关键字

Module ngx_http_rewrite_module
NGINX not equal to – Stack Overflow

# 判断变量是否匹配字符串

if ($var != CN) {
    return 444;
}

if ($var  = EN) {
    return 200;
}

使用变量

Alphabetical index of variables
reverse proxy – nginx – read custom header from upstream server – Stack Overflow

通过 $http_<header-field> 形式,y 以此引用请求头的字段。比如:
1)$http_user_agent:获取请求头的 User-Agent 字段;
2)$http_x_real_ip:引用请求头的 X-Real-IP 字段;

在字符串中使用环境变量:
1)set $foobar "${foo}bar";

常用工具

配置文件生成工具

digitalocean/nginxconfig.io: ⚙️ NGINX config generator on steroids 💉
演示站点:NGINX Config | DigitalOcean
nginx – Merging variable with string in config file – Server Fault

解析工具

crossplane
https://github.com/nginxinc/crossplane

配置文件格式化

Is there a formatter/beautifier for NGINX config files?

对于 Nginx 配置文件的修改或增加,通常是在命令行中是通过 vim 编辑器完成的。

但是,最痛苦的事情就是配置文件的格式化,即配置行的缩进。由于 vim 不会自动缩进 Nginx 配置行,在经过日积月累的修改后,Nginx 配置文件的格式乱七八糟,可读性极低,维护这种配置文件极易出错。

该笔记将记录:如何格式化 Nginx 配置文件,以及常见问题的处理。

命令行工具

Nginx Formatter,目前(05/22/2019)能找到的、Star 比较多的项目(使用 Python 开发),也是我们正在使用的工具:

git clone https://github.com/slomkowski/nginx-config-formatter.git

conf_folder='/etc/nginx/conf.d/'          # 针对 CentOS RHEL 发行版
conf_folder='/etc/nginx/sites-available/' # 针对 Debian Ubuntu 发行版

# 格式化配置文件,同时备份
nginx-config-formatter/nginxfmt.py   \
    -v --backup-original --indent 4  \
    $conf_folder/*.conf

# 如果生成的配置文件符合预期,则进行清理工作(使用 mv 替代 rm 是个好习惯)
find $conf_folder -type f -name '*.conf~' -exec mv -v {} /tmp \;

nginxbeautifier,需要使用 NodeJS 环境来安装运行。但是,我们没有使用该工具,因为在我们的场景中,我们不会为了格式化 Nginx 配置而在主机中安装 NodeJS 环境,否则就把问题搞复杂了。

conffmt,该项目比较久,所以我们也没有使用该工具。

nginxfmt,是我们现在(04/06/2023)正在使用的工具,原因是在服务器中安装比较简单:

# https://pypi.org/project/nginxfmt/
pip3 install nginxfmt

cp nginx.conf nginx.conf.backup
nginxfmt nginx.conf

在线工具

NGINX Beautifier

格式化 Nginx 配置文件,其本质是:配置行的正确缩进。所以仅需合适的缩进工具,进而完全能够借助其他代码格式化工具:Online JavaScript beautifier