执行nginx -t 权限不足

$ nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: [emerg] bind() to 0.0.0.0:80 failed (13: Permission denied)
nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed

原因是自己的nginx.conf配置使用的80端口号,系统默认低于1024的端口号,是需要管理员权限的.

$ sudo nginx -t
sudo: nginx: command not found

使用sudo执行,发现环境变量没有.但是切换root用户,执行是正常的.

$ nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

sudo的环境变量与root权限不一样

`#` env | grep ^PATH
PATH=/usr/local/sbin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/jdk1.7.0_79//bin:/usr/local/nginx//sbin:/root/bin
`#` sudo env | grep ^PATH
PATH=/sbin:/bin:/usr/sbin:/usr/bin

根据上面的环境变量,可以看出,PATH的值是不一样的.

这个问题不仅仅是nginx会出现,不是默认在/sbin:/bin:/usr/sbin:/usr/bin中的可执行文件都可能会存在这种问题.

解决方法

  1. 使用sudo执行命令时,重新指向PATH: sudo -E env "PATH=$PATH" <command> [arguments]

  2. sudo添加别名:alias mysudo='sudo -E env "PATH=$PATH"'

  3. 将执行程序路径添加到sudo默认搜索路径中:

    $ vim /ect/sudoers
    

    找到Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin这一行,注释并添加新内容添加如下内容:

    #Defaults   secure_path = /sbin:/bin:/usr/sbin:/usr/bin
    Defaults    secure_path=/usr/local/sbin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/jdk1.7.0_79//bin:/usr/local/nginx//sbin:/root/bin
    

测试

我使用了方法3,改好保存后:

$ sudo nginx -t
[sudo] password for eoekun: 
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

完美解决!

参考: sudo xxx command not found