How do I restart nginx only after the configuration test was successful on Ubuntu?

jan picture jan · Sep 3, 2013 · Viewed 193.4k times · Source

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.

Answer

Dan Dascalescu picture Dan Dascalescu · May 19, 2015

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.