Nginx 配置 默认虚拟主机

      1.1 默认虚拟主机

  修改主配置文件nginx.conf ,在结束符号 } 上面件一行配置  改写如下

# vim  /usr/local/nginx/conf/nginx.conf

 

意思是 /usr/local/nginx/conf/vhost下面的所有以.conf 结尾的文件都会加载 ,这样我们就可以把所有虚拟主机配置文件放到vhost目录下面了。

# mkidr /usr/local/nginx/conf/vhost

# cd /usr/local/nginx/conf/vhost

# vim default.conf

 

 server 

{

  listen 80 default_server; //有这个default_server标记的就是默认虚拟主机

 server_name aaa.com;

 index index.html index.htm index.php;

root /data/nginx/default;

}

# /usr/local/nginx/sbin/nginx -t 

 

 

# /usr/local/nginx/sbin/nginx -s reload

# echo "default_server"  > /data/nginx/default/index.html 

#curl -x127.0.0.1:80 aaa.com

default_server 

#curl -x127.0.0.1:80 1212.com

 default_server 

 

        1.2 用户认证

# cd /usr/local/nginx/conf/vhost/

# vim test.com.conf

用户认证
server
{
 listen 80;
 server_name test.com;
 index index.html index.htm index.php;
 root /data/nginx/test.com;


location /
 {
 auth_basic "Auth";
 auth_basic_user_file /usr/local/nginx/conf/htpasswd;

}

}

 

 

# yum -y install httpd  //安装httpd 也可以安装之前编译安装的apache2.4

# htpasswd -c /usr/local/nginx/conf/htpasswd aming  //创建aming用户 

 

 

 

 

 

# /usr/local/nginx/sbin/nginx -t 

 

 

 

 

 

 

/usr/local/nginx/sbin/nginx -s reload

 

 核心语句就两行,auth_basic打开认证 auth_basic_user_file指定用户密码文件

 

 

#mkdir /data/nginx/test.com

# echo "test.com" > /data/nginx/test.com/index.html

# curl  -I -x127.0.0.1:80 test.com

 

 

 

 

进入网页输访问 test.com  会出现如下图所示对话框

 

 

 

 

 

 如果针对某个目录做用户认证,需要修改location后面的路径

 

 1.3 域名重定向

server
{
listen 80;
server_name test.com test1.com test2.com;
index index.html index.htm index.php;
root /data/nginx/test.com;

if ($host != 'test.com'){
rewrite ^/(.*)$ http://test.com/$1 permanent;

}
}

 

 

 

 

 

# /usr/local/nginx/sbin/nginx -t 

#/usr/local/nginx/sbin/nginx -s reload

curl -x127.0.0.1:80 -I test1.com/123.txt

 

                     1.4 访问日志

  先来查看Nginx的日志格式

 

 # grep -A2 log_format /usr/local/nginx/conf/nginx.conf

到虚拟主机配置文件中指定访问日志的路径:


server


{
listen 80;
server_name test.com test1.com test2.com;
index index.html index.htm index.php;
root /data/nginx/test.com;


if ($host != 'test.com')
{
rewrite ^/(.*)$ http://test.com/$1 permanent;
}

access_log /tmp/1.log combined_realip;

}

 

 # /usr/local/nginx/sbin/nginx -t 

 # /usr/local/nginx/sbin/nginx -s reload

# curl -x127.0.0.1:80 test.com/111

 

 # cat /tmp/1.log

 

  

# vim  /usr/local/sbin/nginx_log_rotate.sh  写入一下内容

#! /bin/bash
## 假设nginx的日志存放路径为/data/logs/d=`data -d "-1 day" +%Y%m%d`
logdir="/data/logs"
nginx_pid="/usr/local/nginx/logs/nginx.pid"
cd $logdir
for log in `ls *.log`
do
mv $log $log-$d
done
/bin/kill -HUP `cat $nginx_pid`

猜你喜欢

转载自www.cnblogs.com/y0620/p/12145479.html