默认虚拟主机、用户认证、Nginx域名重定向、Nginx访问日志、Nginx日志切割、静态文件不记录日志和过期时间、Nginx防盗链、Nginx访问控制、Nginx解析php相关配置、Nginx代理

一、Nginx默认虚拟主机

在Nginx中也有默认虚拟主机,跟httpd类似,第一个被Nginx加载的虚拟主机就是默认主机,但和httpd不相同的地方是,它还有一个配置用来标记默认虚拟主机,也就是说,如果没有这个标记,第一个虚拟主机为默认虚拟主机。

1、修改主配置文件

[root@123 ~]# vim /usr/local/nginx/conf/nginx.conf       //修改为以下内容
#加入这行,意思是/usr/local/nginx/conf/vhost/下面所有以.conf结尾的都会加载
        include vhost/*.conf;#这里方便实验先注释掉server的内容#    server#    {#        listen 80;#        server_name localhost;#        index index.html index.htm index.php;#        root /usr/local/nginx/html;#        location ~ \.php$ #        {#            include fastcgi_params;#            fastcgi_pass unix:/tmp/php-fcgi.sock;#            fastcgi_index index.php;#            fastcgi_param SCRIPT_FILENAME /usr/local/nginx/html$fastcgi_script_name;#        }    #    }   
}  

2、创建vhost目录及配置文件

[root@123 ~]# mkdir /usr/local/nginx/conf/vhost
[root@123 ~]# cd /usr/local/nginx/conf/vhost
[root@123 vhost]# vim zlinux.conf        //写入以下内容

server
{
   listen 80 default_server;   //有这个标记的就是默认虚拟主机
   server_name zlinux.com;
   index index.html index.htm index.php;
   root /data/wwwroot/default;
}

[root@123 vhost]# mkdir /data/wwwroot
[root@123 vhost]# mkdir /data/wwwroot/default
[root@123 vhost]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@123 vhost]# /usr/local/nginx/sbin/nginx -s reload       //重新加载配置文件

[root@123 vhost]# echo "这是默认主机" > /data/wwwroot/default/index.html
[root@123 vhost]# curl -x127.0.0.1:80 zlinux.com
这是默认主机
[root@123 vhost]# curl -x127.0.0.1:80 11223.com     //访问一个没有定义的网址,一会访问到zlinux.com
这是默认主机


二、用户认证

1、创建一个新的虚拟主机

[root@123 vhost]# vim linuxtest.conf

server
{
   listen 80;                  
   server_name linuxtest.com;
   index index.html index.htm index.php;
   root /data/wwwroot/linuxxtest;

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

[root@123 vhost]# mkdir /data/wwwroot/linuxtest
[root@123 vhost]# yum install -y httpd     //安装httpd,也可以用之前编译安装的apache2
[root@123 vhost]# htpasswd -c /usr/local/nginx/conf/htpasswd 123     //-c选项第一创建用户时使用,否则回清空用户
New password:
Re-type new password:
Adding password for user 123
[root@123 vhost]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@123 vhost]# /usr/local/nginx/sbin/nginx -s reload

两句核心,auth_basic打开认证,auth_basic_user_file指定用户密码文件。生成密码工具需要借助apache的htpasswd。Nginx不自带这个工具。

2、验证

[root@123 vhost]# curl -x127.0.0.1:80 linuxtest.com -I
HTTP/1.1 401 UnauthorizedServer: nginx/1.12.2Date: Tue, 13 Mar 2018 07:38:42 GMTContent-Type: text/htmlContent-Length: 195Connection: keep-aliveWWW-Authenticate: Basic realm="Auth"
//401状态码,说明访问需要验证
[root@123 vhost]# curl -x127.0.0.1:80 -u 123:123456 linuxtest.com      //加上用户名密码就能访问
这是用户认证测试主机


三、域名重定向

Nginx的域名重定向与httpd类似。

[root@123 vhost]# vim moved.conf

server
{
    listen 80;
    #nginx可以配置多个主机名,apache只能使用ServerAlias来指定别名
    server_name testmoved.com testmoved2.com testmoved3.com;
    index index.html index.htm index.php;
    root /data/wwwroot/testmoved;
    #判断host是否为test.com
    if ($host != 'test.com')
    {   
    rewrite ^/(.*)$ http://test.com/$1 permanent;
    }
}

[root@123 vhost]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@123 vhost]# /usr/local/nginx/sbin/nginx -s reload
[root@123 vhost]# mkdir /data/wwwroot/testmoved
[root@123 vhost]# echo "重新定向测试成功" > /data/wwwroot/testmoved/index.html
[root@123 vhost]# curl -x127.0.0.1:80 testmoved.com/
重新定向测试成功
[root@123 vhost]# curl -x127.0.0.1:80 testmoved2.com/ -I
HTTP/1.1 301 Moved Permanently
Server: nginx/1.12.2
Date: Tue, 13 Mar 2018 08:07:21 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: http://testmoved.com/


四、Nginx访问日志

访问日志
Nginx日志格式:

[root@123 ~]# vim /usr/local/nginx/conf/nginx.conf
log_format combined_realip '$remote_addr $http_x_forwarded_for [$time_local]'
    ' $host "$request_uri" $status'
    ' "$http_referer" "$http_user_agent"';

说明:
“combined_ realip”:日志格式名称;’ r e m o t e a d d r http_ x_ forwarded_ for [ t i m e l o c a l ] host “ r e q u e s t u r i " status’ ’ “ h t t p r e f e r e r "" http_ user_ agent”’ :日志内容。
注释:

名称 含义

$remote_addr               客户端IP(公网IP)
$http_x_forwarded_for      代理服务器的IP
$time_local                    服务器本地时间
$host                      访问主机名(域名)
$request_uri               访问的URL地址
$status                        状态码
$http_referer              referer
$http_user_agent           user_agent

定义虚拟主机日志格式

定义虚拟主机的前提是在Nginx配置文件中设定日志格式,然后才能在虚拟主机中进行调用(格式名称)

[root@123 ~]# cd /usr/local/nginx/conf/vhost/
[root@123 vhost]# ls
aaa.com.conf  test.com.conf

定义test.com.conf日志格式:  
[root@123 vhost]# vim test.com.conf  
 ……
 access_log /tmp/test.com.log combined_realip;
    #指定日志位置及格式

检查错误:
[root@123 vhost]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

如果不指定日志格式,系统使用默认日志格式,记录内容较简单

检测

[root@123 vhost]# curl -x127.0.0.1:80 test.com
This is test.com
[root@123 vhost]# cat /tmp/test.com.log 
127.0.0.1 - [11/Aug/2017:15:09:54 +0800] test.com "/" 200 "-" "curl/7.29.0"


五、Nginx日志切割

因为Nginx没有自带的日志切割工具,所以需要借助系统日志切割命令或使用日志切割脚本。

日志切割脚本

为了方便管理,shell脚本统一保存位置:/usr/local/sbin/

[root@123 vhost]# vim /usr/local/sbin/nginx_log_rotate.sh

#! /bin/bash
d=`date -d "-1 day" +%Y%m%d` 
#定义切割时间(切割一天前的日志)
logdir="/tmp/"
#此处指定要切割的日志路径(该路径来自虚拟主机配置文件)
nginx_pid="/usr/local/nginx/logs/nginx.pid"
#调用pid的目的是执行命令:/bin/kill -HUP `cat $nginx_pid`
#该命令等价于命令:nginx -s reload(重新加载文件),确保与虚拟主机配置文件变更保持同步
#该地址来自nginx配置文件
cd $logdir
for log in `ls *.log`
do
    mv $log $log-$d
done
#此处使用通配进行循环,对所有复合条件的日志文件进行切割
/bin/kill -HUP `cat $nginx_pid`
#执行此命令进行重载生成新的日志文件来记录新的日志

执行该脚本

[root@123 vhost]# sh -x /usr/local/sbin/nginx_log_rotate.sh
++ date -d '-1 day' +%Y%m%d
+ d=20170810
+ logdir=/tmp/
+ nginx_pid=/usr/local/nginx/logs/nginx.pid
+ cd /tmp/
++ ls test.com.log yum.log
+ for log in '`ls *.log`'
+ mv test.com.log test.com.log-20170810
+ for log in '`ls *.log`'
+ mv yum.log yum.log-20170810
++ cat /usr/local/nginx/logs/nginx.pid
+ /bin/kill -HUP 1251

-x选项的作用是显示脚本执行过程。

该脚本配合任务计划cron使用,定期进行切割和清理


六、静态文件不记录日志&过期时间

核心配置参数

[root@123 vhost]# vim test.com.conf
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
    #匹配文件类型
    {
          expires      7d;
          #过期时间为7天
          access_log off;
          #不记录该类型文件的访问日志
    }
location ~ .*\.(js|css)$
    {
          expires      12h;
          #过期时间为12小时
          access_log off;
          #不记录该类型文件的访问日志
    }
    access_log /tmp/test.com.log combined_realip;
    #指定日志位置及格式

检测

[root@123 vhost]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@adailinux vhost]# /usr/local/nginx/sbin/nginx -s reload

访问index.html:
[root@123 vhost]# !curl
curl -x127.0.0.1:80 test.com
This is test.com

[root@123 vhost]# !cat
cat /tmp/test.com.log 
127.0.0.1 - [11/Aug/2017:17:45:28 +0800] test.com "/" 200 "-" "curl/7.29.0"
即:有日志!

访问baidu.png文件:
[root@123 test.com]# curl -x127.0.0.1:80 test.com/baidu.png -I
HTTP/1.1 200 OK
Server: nginx/1.12.1
Date: Fri, 11 Aug 2017 09:47:57 GMT
Content-Type: image/png
Content-Length: 3706
Last-Modified: Tue, 01 Aug 2017 10:13:45 GMT
Connection: keep-alive
ETag: "59805459-e7a"
Expires: Fri, 18 Aug 2017 09:47:57 GMT
Cache-Control: max-age=604800
Accept-Ranges: bytes
说明:max-age=604800s=7天,即该文件缓存的过期时间为7天!

[root@123 test.com]# cat /tmp/test.com.log 
127.0.0.1 - [11/Aug/2017:17:45:28 +0800] test.com "/" 200 "-" "curl/7.29.0"
即:无该文件的访问日志!!!


七、Nginx防盗链

因为该配置也使用location板块,所以本节可结合日志管理一起配置

[root@123 ~]# vim /usr/local/nginx/conf/vhost/test.com.conf
……
location ~* ^.+\.(gif|jpg|png|swf|flv|rar|zip|doc|pdf|gz|bz2|jpeg|bmp|xls)$
{
    expires 7d;
    valid_referers none blocked server_names  *.test.com ;
    #定义referer白名单
    if ($invalid_referer) {
        return 403;
    #if函数的意思是:如果不是白名单内的域名,返回值:403
    }
    access_log off;
}
……

[root@123 ~]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@123 ~]# /usr/local/nginx/sbin/nginx -s reload

“location ~* ^.+”在此0“ * ”的作用是后面匹配的内容不区分大小写

检测

[root@123 ~]# curl -e "http://www.baidu.com/1.txt" -x127.0.0.1:80 -I test.com/baidu.png
HTTP/1.1 403 Forbidden
Server: nginx/1.12.1
Date: Mon, 14 Aug 2017 06:22:36 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive

使用非白名单内的referer进行访问,被拒绝


八、Nginx访问控制

需求:访问/admin/目录的请求,只允许几个指定IP通过,配置如下

[root@123 ~]# vim /usr/local/nginx/conf/vhost/test.com.conf 
……
location /admin/
    {
    allow 192.168.8.132;
    allow 127.0.0.1;
    deny all;
    #设置IP白名单
    }
……

[root@123 ~]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@123 ~]# /usr/local/nginx/sbin/nginx -s reload

创建上面指定的目录

[root@123 ~]# mkdir /data/wwwroot/test.com/admin
[root@123 ~]#  echo “test,test”>/data/wwwroot/test.com/admin/1.html

测试

[root@123 ~]# curl -x127.0.0.1:80  test.com/admin/1.html
“test,test”

[root@123 ~]# curl -x192.168.8.132:80  test.com/admin/1.html
“test,test”

访问控制——正则匹配

location ~ .*(abc|image)/.*\.php$
{
        deny all;
}

访问控制——user_agent限制

if ($http_user_agent ~ 'Spider/3.0|YoudaoBot|Tomato')
{
      return 403;
}

deny all和return 403效果一样

九、Nginx解析PHP相关配置

核心配置

vim /usr/local/nginx/conf/vhost/test.com.conf
……
location ~ \.php$
    {
        include fastcgi_params;
        #fastcgi_pass 127.0.0.1:9000
        fastcgi_pass unix:/tmp/php-fcgi.sock;
        ##fastcgi_pass两种监听格式,但是要保证Nginx和php-fpm中格式一致
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /data/wwwroot/test.com$fastcgi_script_name;
    }

在此注意两点,fastcgi_pass有两种格式,但是无论使用哪种格式都有保证Nginx和php-fpm中格式一致,否则会报错502;fastcgi _param SCRIPT _FILENAME所在行的路径要和root路径一致

十、Nginx代理

Nginx代理是一种反向代理。反向代理(Reverse Proxy)方式是指以代理服务器来接受Internet上的连接请求,然后将请求转发给内部网络上的服务器;并将从服务器上得到的结果返回给Internet上请求连接的客户端,此时代理服务器对外就表现为一个服务器

工作原理

Nginx代理是在一台代理服务器中自定义一个域名,该域名指向一个IP,然后将用户的请求通过这台代理服务器访问指定的IP所对应的web服务器。

graph LR
用户-->代理服务器
代理服务器-->用户
代理服务器-->web服务器
web服务器-->代理服务器

进入虚拟主机目录:

[root@123 ~]# cd /usr/local/nginx/conf/vhost/

创建代理服务器

[root@123 vhost]# vim proxy.conf
server
{
    listen 80;
    server_name ask.apelearn.com;
    #定义域名(一般和被代理ip的域名保持一致)
    location /
    {
        proxy_pass      http://121.201.9.155/;
        #指定被代理(被访问)的IP(web服务器IP)
        proxy_set_header Host   $host;
        #$host指的是代理服务器的servername(也是被代理IP的域名)
        proxy_set_header X-Real-IP      $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

说明: 因为该虚拟主机只用作代理服务器,不需要访问本地文件,所以不需要设置根目录。

检测
设置代理前

[root@123 vhost]# curl -x127.0.0.1:80 ask.apelearn.com/robots.txt
<html>
<head><title>404 Not Found</title></head>
<body bgcolor="white">
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.12.1</center>
</body>
</html>

设置代理后

[root@123 vhost]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@123 vhost]# /usr/local/nginx/sbin/nginx -s reload


[root@123 vhost]# curl -x127.0.0.1:80 ask.apelearn.com/robots.txt
#
# robots.txt for MiWen
#

User-agent: *

Disallow: /?/admin/
Disallow: /?/people/
Disallow: /?/question/
Disallow: /account/
Disallow: /app/
Disallow: /cache/

扩展:

nginx.conf 配置详解 http://www.ha97.com/5194.html http://my.oschina.net/duxuefeng/blog/34880
nginx rewrite四种flag http://www.netingcn.com/nginx-rewrite-flag.html http://unixman.blog.51cto.com/10163040/1711943
502问题汇总 http://ask.apelearn.com/question/9109
location优先级 http://blog.lishiming.net/?p=100

猜你喜欢

转载自blog.csdn.net/iamfishhh/article/details/80938006