以非root用户身份运行Nginx

Sar*_*ith 13 linux nginx centos7

我使用Ansible安装了Nginx.要在Centos7上安装,我使用了yum软件包,因此它默认以root用户身份运行.我希望它在Centos框中以不同的用户(ex- nginx用户)启动和运行.当我尝试使用其他用户运行它时,我收到以下错误:

nginx.service的作业失败,因为控制进程退出并显示错误代码.有关详细信息,请参阅"systemctl status nginx.service"和"journalctl -xe".

我知道以root身份运行是不可取的.那么我该如何解决这个问题并以非root用户身份运行nginx.谢谢

Far*_*ahi 25

添加/更改以下内容/etc/nginx/nginx.conf:

user nginx;
Run Code Online (Sandbox Code Playgroud)

您应该创建用户并以递归方式授予webroot目录的权限.

这种方式只有主进程运行为root.因为:只有root进程可以侦听1024以下的端口.Web服务器通常在端口80和/或443上运行.这意味着它需要以root身份启动.

以非root用户身份运行master进程:

更改以下所有权:

  • error_log中
  • 访问日志
  • PID
  • client_body_temp_path
  • fastcgi_temp_path
  • proxy_temp_path
  • scgi_temp_path
  • uwsgi_temp_path

将listen指令更改为1024以上的端口,以所需用户身份登录并运行nginx nginx -c /path/to/nginx.conf


小智 9

以防万一它有助于在 2020 年遇到这个问题的人,这是我的最小 nginx.conf,用于在端口 8088 上运行 Web 服务器,适用于非 root 用户。无需修改文件权限!(在 Centos 7.4 和 nginx 1.16.1 上测试)

    error_log /tmp/error.log;
    pid       /tmp/nginx.pid;
    
    events {
      # No special events for this simple setup
    }
    http {
      server {
        listen       8088;
        server_name  localhost;
    
        # Set a number of log, temp and cache file options that will otherwise
        # default to restricted locations accessible only to root.
        access_log /tmp/nginx_host.access.log;
        client_body_temp_path /tmp/client_body;
        fastcgi_temp_path /tmp/fastcgi_temp;
        proxy_temp_path /tmp/proxy_temp;
        scgi_temp_path /tmp/scgi_temp;
        uwsgi_temp_path /tmp/uwsgi_temp;
    
        # Serve local files
        location / {
          root /home/<your_user>/web;
          index  index.html index.htm;
          try_files $uri $uri/ /index.html;
        }
      }
    }
Run Code Online (Sandbox Code Playgroud)


小智 7

为了以防万一,出于测试/调试的目的,有时我会以非特权用户身份在Debian(拉伸)笔记本电脑上运行nginx实例。

我使用像这样的最小配置文件:

worker_processes 1;
error_log stderr;
daemon off;
pid nginx.pid;

events {
  worker_connections  1024;
}

http {
  include             /etc/nginx/mime.types;
  default_type        application/octet-stream;

  sendfile on;

  keepalive_timeout   65;

  ssl_protocols TLSv1 TLSv1.1 TLSv1.2; 
  ssl_prefer_server_ciphers on;
  access_log access.log;
  server {
    listen            8080;
    server_name       localhost;

    location / {
      include /etc/nginx/uwsgi_params;
      uwsgi_pass localhost:8081;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,我开始以下过程:

/usr/sbin/nginx -c nginx.conf -p $PWD
Run Code Online (Sandbox Code Playgroud)