How do I restart nginx only after the configuration test was successful on Ubuntu?
When I restart the nginx service on a command line on an Ubuntu server, the service crashes when a nginx configuration file has errors. On a multi-site server this puts down all the sites, even the ones without configuration errors.
To prevent this, I run the nginx configuration test first:
nginx -t
After the test ran successful, I could restart the service:
/etc/init.d/nginx restart
Or only reload the nignx site configs without a restart:
nginx -s reload
Is there a way to combine those two commands where the restart command is conditional to the configuration test's result?
I couldn't find this online and the official documentation on this is rather basic. I don't know my way around Linux that well, so I don't know if what I'm looking for is right in front of me or not possible at all.
I'm using nginx v1.1.19.
Solution 1:
As of nginx 1.8.0, the correct solution is
sudo nginx -t && sudo service nginx reload
Note that due to a bug, configtest
always returns a zero exit code even if the config file has an error.
Solution 2:
Actually, as far as I know, nginx would show an empty message and it wouldn't actually restart if the configuration is bad.
The only way to screw it up is by doing an nginx stop and then start again. It would succeed to stop, but fail to start.
Solution 3:
I use the following command to reload Nginx (version 1.5.9) only if a configuration test was successful:
/etc/init.d/nginx configtest && sudo /etc/init.d/nginx reload
If you need to do this often, you may want to use an alias. I use the following:
alias n='/etc/init.d/nginx configtest && sudo /etc/init.d/nginx reload'
The trick here is done by the "&&" which only executes the second command if the first was successful. You can see here a more detailed explanation of the use of the "&&" operator.
You can use "restart" instead of "reload" if you really want to restart the server.
Solution 4:
alias nginx.start='sudo nginx -c /etc/nginx/nginx.conf'
alias nginx.stop='sudo nginx -s stop'
alias nginx.reload='sudo nginx -s reload'
alias nginx.config='sudo nginx -t'
alias nginx.restart='nginx.config && nginx.stop && nginx.start'
alias nginx.errors='tail -250f /var/logs/nginx.error.log'
alias nginx.access='tail -250f /var/logs/nginx.access.log'
alias nginx.logs.default.access='tail -250f /var/logs/nginx.default.access.log'
alias nginx.logs.default-ssl.access='tail -250f /var/logs/nginx.default.ssl.log'
and then use commands "nginx.reload" etc..