Nginx虚拟主机以及自动启动脚本详解
想要部署Nginx虚拟主机,那么首先需要nginx的环境,那么我们一起来看一下吧
systemctl stop firewalld
iptables -F
setenforce 0
1)安装支持软件
yum -y install pcre-devel zlib-devel openssl-devel
2)创建运行用户,组
useradd -M -s /sbin/nologin nginx
3)编译安装nglinx
tar xf nglix-1.14.2.tar.gz -C /usr/src
4)配置编译
cd /usr/src/nginx-1.14.2
./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_stub_status_module --with-http_ssl_module --with-http_flv_module --with-http_gzip_static_module && make && make install
为了使nginx服务器运行方便,可以为主程序nginx 创建链接文件,以便管理员直接执行nginx命令
ln -s /usr/local/nginx/sbin/nginx /usr/local/bin
ll /usr/local/bin/nginx
5)nginx运行控制
nginx -t 检测语法
6)启动,停止nginx,如果服务器中已安装有httpd等其他web 服务软件,应关闭避免冲突
netstat -anpt |grep :80
nginx
netstat -anpt |grep :80
查看httpd:192.168.30.22窗口
welocome to nginx!
killall -s HUP nginx 重载配置
killall -s QULT nginx 退出进程
killall -9
netstat -anpt |grep :80
为了更好管理nginx进程写个脚本并使用chkconfig工具来进行管理
vim /etc/init.d/nginx
#!/bin/bash
#chkconfig:2345 99 20
PROG="/usr/local/nginx/sbin/nginx"
PIDF="/usr/local/nginx/logs/nginx.pid"
case "$1" in
start)
$PROG
;;
stop)
kill -s QUIT $(cat $PIDF)
;;
restart)
$0 stop
$0 start
;;
reload)
kill -s HUP $(cat $PIDF)
;;
*)
echo "Usage:$0{start|stop|restart|reload}"
exit 1
esac
exit 0
netstat -anpt |grep :80
给上权限
chmod +x /etc/init.d/nginx
chkconfig --add nginx
chkconfig nginx on
chkconfig --list nginx
然后测试脚本
/etc/init.d/nginx stop
netstat -anpt |grep :80
/etc/init.d/nginx start
netstat -anpt |grep :80
我这里并做了一个小的配置,查看/status下可以看到用户的访问量
在http{}配置的server{} 子配置文件内添加如下配置项
vim /usr/local/nginx/conf/nginx.conf
location /status {
stub_status on;
access_log off;
}
systemctl restart nginx
浏览器访问http://192.168.30.22/status
虚拟主机应用
mkdir /usr/local/nginx/html/zc
mkdir /usr/local/nginx/html/cloud
echo "<h1>www.zc.com</h1>"> /usr/local/nginx/html/zc/index.html
echo "<h1>www.cloud.com</h1>" > /usr/local/nginx/html/cloud/index.html
vim /usr/local/nginx/conf/nginx.conf
user nginx;
worker_processes 2;
error_log logs/error.log;
error_log logs/error.log notice;
error_log logs/error.log info;
pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log logs/access.log main;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name www.zc.com;
charset utf-8;
access_log logs/zc.access.log main;
location / {
root html/zc;
index index.html index.htm;
}
}
server {
listen 81;
server_name www.cloud.com;
charset utf-8;
access_log logs/cloud.access.log main;
location / {
root html/cloud;
index index.html index.html;
}
}
}
systemctl restart nginx
vim /etc/hosts
192.168.30.24 www.zc.com
192.168.30.24 www.cloud.com
虚拟主机访问测试 elinks 命令需要yum -y install elinks安装
elinks --dump http://www.zc.com
elinks --dump http://www.cloud.com:81
http://192.168.30.24
http://192.168.30.24:81