nginx的基本使用

Nginx是一款轻量级的网页服务器、反向代理服务器。相较于Apache、lighttpd具有占有内存少,稳定性高等优势。它最常的用途是提供反向代理服务。关于nginx的安装,网上有很多教程,大家都可以去百度上查找。这篇文章是来记录nginx的基本使用和配置中遇到的错误问题。

基本使用

环境配置
将命令脚本超链接到环境变量中

1
$ ln -sf /usr/local/nginx/sbin/nginx /usr/local/bin/nginx

启动

1
$ nginx

停止

1
$ nginx -s [start, stop]

重新启动

1
$ nginx -s reopen

修改 nginx.conf 后进行测试是否没有语法错误

1
$ nginx -t

然后重新加载配置,使之生效

1
$ nginx -s reload

系统命令的方式来启动停止

1
$ sudo systemctl [start, stop, restart] nginx

设置是否自动开机自启动

1
$ sudo systemctl [enable, disable] nginx

常见错误

1、nginx: [error] invalid PID number “” in “/run/nginx.pid”
nginx -s reloadnginx: [error] invalid PID number "" in "/run/nginx.pid"错误
遇到这个错误,需要先执行

1
$ nginx -c /etc/nginx/nginx.conf 

nginx.conf文件的路径可以从nginx -t的返回中找到。
这时候如何没有报错,那么你就可以nginx -s reload
如果还错误,请看第二个问题
2、nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
错误详情

1
2
3
4
5
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] still could not bind()

错误描述:地址已被使用。可能nginx服务卡死了,导致端口占用。
查看nginx的运行情况

1
$ ps aux | grep nginx

结果

1
2
3
4
root     13332  0.0  0.0  56824  2796 ?        Ss   17:00   0:00 nginx: master process nginx -c /etc/nginx/nginx.conf
nginx 13437 0.0 0.0 57360 3792 ? S 17:09 0:00 nginx: worker process
nginx 13438 0.0 0.0 57228 3776 ? S 17:09 0:00 nginx: worker process
root 13854 0.0 0.0 112676 992 pts/0 S+ 18:09 0:00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn nginx

使用kill指令删除进程

1
$ kill -9 13332 13437 13438

然后nginx -s reload刷新
3、nginx绑定域名,发现使用域名访问不成功,用ip访问成功
出现这种情况一般是因为你的服务器安全组没有设置相应的端口访问,比如http,需要设置80端口可以访问,https设置443端口。