nginx相关配置详解

一、nginx默认虚拟主机

删除nginx.conf配置文件中的server段代码,并在http段中添加下面一行配置文件。

#打开nginx配置文件
vim nginx.conf
#添加虚拟主机配置文件目录
include vhost/*.conf

在当前目录下面创建vhost目录,然后就可以在vhost目录里边添加虚拟主机的配置文件了。

#创建虚拟主机配置文件目录
mkdir vhost

二、nginx用户认证

2.1对整体进行认证

创建一个虚拟主机配置文件如下

server
{
  listen 80;
  server name www.cnbugs.com;
  index index. htm index.html index.php;
  root /data/www/www.cnbugs.com;
location /
  {
    auth basic "Auth";
    auth_basic user _file /etc/htpasswd;
  }
}

nginx用户认证需要用到apache的httpd-tools包,如果没有htpasswd这个命令,可以使用以下方式进行安装即可。

yum install httpd-tools -y

使用如下命令生成

#为用户创建认证,制定文件路径
[root@localhost ~]# htpasswd -c /etc/htpasswd cnbugs
New password: 
Re-type new password: 
Adding password for user cnbugs
#查看
[root@localhost ~]# cat /etc/htpasswd 
cnbugs:$apr1$vu0KHxlq$Rnr21V2j3r0Avc3Qt701/.

2.2对某目录进行认证

针对目录做用户认证,例如对admin目录做认证,只需要把配置文件中的location /改为location /admin/即可,配置文件如下

location /admin/
  {
    auth basic "Auth";
    auth_basic user _file /etc/htpasswd;
  }

2.3对某文件做用户认证

对某文件做认证,还是需要修改location部分,例如对admin.php进行做认证,修改为如下

location ~ admin.php
  {
    auth basic "Auth";
    auth_basic user _file /etc/htpasswd;
  }

三、nginx域名跳转

域名重定向,就是把一个域名重定向到另一个域名中,一般把一个顶级域名重定向到www中。

server
{
  listen 80;
  server name cnbugs.com www.cnbugs.com;
  index index. htm index.html index.php;
  root /data/www/www.cnbugs.com;
  if ($host != 'cnbugs.com'){
    rewrite ^/(.*)$ http://cnbugs.com/$1 permanent;
  }
}

四、nginx访问日志

nginx的配置文件中log_format,log_format是定义nginx访问日志的格式,代码和格式含义如下。

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                   '"$http_user_agent" "$http_x_forwarded_for"';
  • $remote_addr:客户端IP(公网IP)
  • $http_x_forwarded_for:代理服务器IP
  • $time_local:服务器本地时间
  • $host:访问主机名(域名〉。
  • $request_ uri:访问的URL地址。
  • $status:状态码。
  • $httpd一referer:每个页面的引用记录、页面统计。
  • $http_ user_ agent:用户代理。

定义完之后需要在server模块里边进行定义

access_log /usr/local/nginx/logs/access.log main

五、nginx日志切割

nginx日志切割工具需要借助脚本去实现,脚本如下

#!/bin/bash
##定义Nginx日志路径为/data/logs/nginx/
##_author is humingzhe
##emai1 admin@humingzhe.com 
d=`date-d "-1 day"+%Y%m%d`
1ogdir="/data/logs/nginx/"
nginx_pid="/usr/local/nginx/1ogs/nginx.pid"
cd $logdir 
for log in `1s *.1og` 
do 
    mv $log $d-$1og 
done
/bin/ki11 -HUP `cat $nginx_pid`

把脚本加入定时任务,每天执行就可以了

发表评论

后才能评论