9

格式化 nginx 配置文件

 2 years ago
source link: https://www.codewoody.com/posts/57148/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Published Apr 13, 2022

格式化 nginx 配置文件

这里说的格式化不是格式化硬盘的意思,而是只美化代码/配置文件的意思。

自己手搓 Nginx 配置的时候一般都不注意缩进,然后就把格式弄的很乱,不容易查看了。这篇文章研究如何使用一些工具来美化 Nginx 的配置文件。

2d7a8a90ebc4f43195b7515d8e48b980.png

这种工具其实比较多,我参考的 How to format and beautify Nginx configuration 这篇文章。文章里面提到了很多工具,这里我只列出其中一种。

下面这个工具有个严重的问题。如果在 Nginx 配置内容中出现分号,那么这个工具会在分号后面添加换行符;例如

add_header Strict-Transport-Security 'max-age=15552000;includeSubDomains;preload' always;

会被转化成:

add_header Strict-Transport-Security 'max-age=15552000;
includeSubDomains;
preload' always;

神奇的是这种问题 nginx -t 检查不出来,但是会导致 Nginx 报出神奇的错误(如 ERR_HTTP2_PROTOCOL_ERROR),因此这个工具要慎用;

首先我们从 Github 上拉取代码:

$ git clone https://github.com/1connect/nginx-config-formatter.git

然后可以将可执行文件 nginxfmt.py 拷贝到 /usr/local/bin 中。如果只是临时使用,可以不用拷贝,直接使用 nginxfmt.py 即可。

这个工具的使用非常简单,直接在脚本后面添加要优化的配置文件即可。脚本的 Help 信息如下:

$ nginxfmt.py -h
usage: nginxfmt.py [-h] [-v] [-b] config_files [config_files ...]

This Python script formats nginx configuration files in consistent way.
Originally published under https://github.com/1connect/nginx-config-formatter

positional arguments:
config_files configuration files to format

optional arguments:
-h, --help show this help message and exit
-v, --verbose show formatted file names
-b, --backup-original
backup original config file

在 Linux 环境下关闭交换区的方法


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK