Nginx默认虚拟主机配置

Nginx源码包安装的配置文件/usr/local/nginx/conf/nginx.conf

注释掉server{},增加http{include vhost/*.conf;}

mkdir /usr/local/nginx/conf/vhost

vim /usr/local/nginx/conf/vhost/apeng.com.conf

server
{
    listen 80 default_server;
    server_name www.apeng.com;
    index index.html index.htm index.php;
    root /data/wwwroot/default;
}

mkdir -p /data/wwwroot/default

vim /data/wwwroot/default/index.html

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

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

iptables -I INPUT -p tcp --dport 80 -j ACCEPT

windows中的C:\Windows\System32\drivers\etc\hosts中设置ip与域名的对应关系

浏览器中测试http://www.apeng.com/    

curl localhost

默认虚拟主机/usr/local/nginx/conf/vhost/00.conf或0.conf,第一个就是虚拟主机,在配置文件中定义default_server


Nginx的用户认证

/usr/local/nginx/conf/vhost/auth.com.conf

server
{
    listen 80;
    server_name www.auth.com;
    index index.html index.htm index.php;
    root /data/wwwroot/auth.com;
location / 或 /dir 或 ~admin.php
  {
  	auth_basic "Auth";
	auth_basic_user_file /usr/local/nginx/conf/htpasswd;
  }
}

yum install httpd -y

htpasswd -c /usr/local/nginx/conf/htpasswd apeng

mkdir /data/wwwroot/auth.com

echo "authorized" > /data/wwwroot/auth.com/index.html

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

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

curl -x127.0.0.1:80 -uapeng:123 www.auth.com    


Nginx域名重定向

vim /usr/local/nginx/conf/vhost/rewrite.com.conf

server
{
    listen 80;
    server_name www.rewrite.com www.rewrite1.com www.rewrite2.com;
    index index.html index.htm index.php;
    root /data/wwwroot/rewrite.com;
    if ($host != 'www.rewrite.com' ){
        rewrite ^/(.*)$ http://www.rewrite.com/$1 permanent; //permanent 301;redirect 302
    }
}

mkdir -p /data/wwwroot/rewrite.com

echo "rewrite.com" > /data/wwwroot/rewrite.com/index.html

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

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

curl -x127.0.0.1:80 www.rewrite1.com    


Nginx访问日志

日志格式 

vim /usr/local/nginx/conf/nginx.conf  //搜索log_format

image.png

$remote_addr客户端ip(公网ip)
$http_x_forwarded_for代理服务器的ip
$time_local服务器本地时间
$host访问主机名(域名)
$request_uri访问的url地址
$status状态码
$http_refererreferer
$http_user_agentuser_agent

查看本机公网ip

image.png

除了在主配置文件nginx.conf里定义日志格式外,还需要在虚拟主机配置文件中增加

        access_log /tmp/1.log combined_realip(与nginx.conf中定义的日志格式名一样)

 -t && -s reload

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

 cat /tmp/1.log


Nginx的日志切割

vim /usr/local/sbin/nginx_log_rotate.sh

#!/bin/bash
d=`date -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`

任务计划

crontab -e
0 0 * * * /bin/bash /usr/local/sbin/nginx_log_rotate.sh