我正在尝试编写一个函数,在将文件移动到/etc/nginx/site-available
之前对其执行健全检查。
位于我的主目录中,并定期进行修改。
在这些文件中所做的唯一修改是添加server_name
。
它们看起来像:
server {
listen 80;
server_name domain.com;
server_name www.domain.com;
server_name mynsite1.com;
server_name www.mysite1.com;
server_name mysite2.com;
server_name www.mysite2.com;
server_name mysite3.com;
server_name www.mysite3.com;
server_name mysite4.com;
server_name www.mysite4.com;
access_log /var/log/nginx/domain.com-access.log main;
error_log /var/log/nginx/domain.com-error.log warn;
root /var/www/docroot;
index index.php index.html index.htm;
location / {
try_files $uri /app_dev.php;
}
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
# NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
location ~ /\.ht {
deny all;
}
}
这是我现在的功能:
verify_nginx()
{
if [ ! -s "$file1" ]; then
echo "-> File \"$file1\" is empty or do not exist" | ts
exit 1
elif [ ! -s "$file2" ]; then
echo "-> File \"$file2\" is empty or do not exist" | ts
exit 1
fi
}
我还想在函数中添加
nginx -t -c /homedir/file1
,但得到以下错误:nginx: [emerg] "server" directive is not allowed here in /homedir/file:1
nginx: configuration file /homedir/file test failed
实际上,
nginx -c
需要的是nginx.conf
,它不包括homedir中的文件。我可以将文件放入
/etc/nginx/site-available
中,该文件包含在nginx.conf
中,但我希望在将文件移动到正确位置之前执行健全性检查。我的问题:
是否有方法使用
/etc/nginx/site-available
测试位于nginx
之外的配置文件?应该对
nginx
文件执行什么样的健全性检查? 最佳答案
您试图进行正常检查的文件不是nginx配置文件,因此(可以理解的是)nginx -t
表示它们无效。-c
标志需要“an alternative configuration file”,而不是单个server
块。server
块位于http
块内。
如果你想运行nginx -t
你需要给它一个正确的配置文件,其中包括你试图修改的文件。正如Etan Reisner所建议的那样,您可以简单地编写一个包含您的文件的虚拟nginx.conf
,类似这样的操作可能有效(我不在安装了nginx atm的机器上,因此您可能需要添加更多存根指令):
http {
include path/to/files/*;
}
然后可以运行
nginx -t -c dummy_nginx.conf
。但这有一个问题;您仍然可能有任何数量的错误,这些错误只有在加载真正的配置文件时才会显示出来。
相反,您可以在加载更改之前使用更改来验证真正的配置文件,方法是在
nginx -t
之前调用reload
;如果需要,可以将其包装到bash函数中:safe_reload() {
nginx -t &&
service nginx reload # only runs if nginx -t succeeds
}
您还应该有某种备份或还原机制。这可以简单地将旧的配置文件复制到并行的
*.bak
文件中,但更令人愉快的是使用像Mercurial或Git这样的VCS。您签入成功的配置的每个迭代,然后如果出现任何错误,您可以轻松地恢复到以前的已知良好配置。