Running Nginx as non root user

Sarith picture Sarith · Feb 19, 2017 · Viewed 62.8k times · Source

I installed Nginx using Ansible. To install on Centos7 I used the yum package so it by default was run as root user. I want it to start and run as a different user (ex - nginx user) in the Centos box. When I try to run it with a different user I get the following error:

Job for nginx.service failed because the control process exited with error code. See "systemctl status nginx.service" and "journalctl -xe" for details.

I know it's not advisable to run as root. So how do I get around this and run nginx as a non root user. Thanks

Answer

Farhad Farahi picture Farhad Farahi · Feb 19, 2017

Add/Change the following in your /etc/nginx/nginx.conf:

user nginx;

You should create the user and grant permissions on the webroot directories recursively.

This way only master process runs as root. Because: Only root processes can listen to ports below 1024. A webserver typically runs at port 80 and/or 443. That means it needs to be started as root.

To run master process as non root user:

Change the ownership of the following:

  • error_log
  • access_log
  • pid
  • client_body_temp_path
  • fastcgi_temp_path
  • proxy_temp_path
  • scgi_temp_path
  • uwsgi_temp_path

Change the listen directives to ports above 1024, log in as desired user and run nginx by nginx -c /path/to/nginx.conf