与apache服务器类似,nginx也有基于域名,IP及端口的虚拟主机配置,在实际工作场景中,基于域名的虚拟主机配置较常见。
nginx服务的主要配置文件nginx.conf
[root@lnmp01 conf]# ls -l nginx.conf
-rw-r--r-- 1 root root 2788 Jan 14 17:41 nginx.conf
[root@lnmp01 conf]# pwd
/application/nginx/conf

去掉注释及空行后的配置文件
[root@lnmp01 conf]# egrep -v "#|^$" nginx.conf
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}

默认虚拟主机为localhost,
这里配置虚拟,可以配置两个,中间用空格隔开
如 server_name www.tuwei.com tuwei.com
配置完后如下
[root@lnmp01 conf]# egrep -v "#|^$" nginx.conf
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name www.tuwei.org tuwei.org;
location / {
root html/www;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}

配置站点文件
[root@lnmp01 conf]# echo "hi.Im tuwei,my 51cto's blog is https://blog.51cto.com/tuwei">../html/www/index.html
将IP和域名加到本地hosts文件中
echo "192.168.132.20 www.tuwei.org">>/etc/hosts
检查语法
sbin/nginx -t
重启nginx服务
[root@lnmp01 conf]# kill -HUP cat ../logs/nginx.pid
或者用
../sbin/nginx -c /application/nginx/conf/nginx.conf
../sbin/nginx -s reload

本机测试
[root@lnmp01 conf]# curl www.tuwei.org
hi.Im tuwei,my 51cto's blog is https://blog.51cto.com/tuwei
如果在电脑上访问该域名,需要在电脑hosts文件中作解析。

基于端口的虚拟主机----次重要

基于IP的虚拟主机------不重要----企业一般用负载均衡配ip

listen IP:80;
server_name IP;

  nginx日志

worker_processes 1;

error_log /application/logs/err.log crit;------->crit为日志级别
events {
use epoll;------------------------------->
worker_connections 1024;
}

日志格式
配置文件中有,去掉注释
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';

访问日志
location / {
root html/www;
index index.html index.htm;
}
access_log /application/logs/host.access.log main;-------->
可以用命令awk '{print $1}' host.access.log |sort|uniq -c|sort -rn -k1 通过日志分析访问网站的IP情况
nginx状态信息配置
在基于域名配置中加入
server {
listen 80;
server_name status.tuwei.org
location / {
stub_status on;
access_log off;

}

}
也可以针对具体的ip进行设置

stub_status on;
access_log off;
allow 192.168.132.10-------》只允许该ip访问
deny all
之前提到访问站点时提示403错误,除了没有首页文件,站点文件权限不足,还有就是配置中做了allow,deny权限控制。
访问192.168.132.20得到如下信息
Active connections: 4
server accepts handled requests
23 23 49
Reading: 0 Writing: 1 Waiting: 3

第一个server表示nginx启动到现在共处理了23个连接
第二个accepts表示nginx启动到现在成功创建了23次握手
第三个handled requests,表示共处理了49次请求

Reading:nginx读取到客户端的Header信息数
Writing:nginx返回给客户端的Header信息数
Waiting:已经处理完正在等候下一次请求指令的驻留连接