2018-09-20直播笔记

 

目录

 

 

默认虚拟主机

配置方式

测试访问

Nginx用户认证

配置方式

测试效果

针对目录的用户认证

测试效果

针对文件的用户认证

测试效果

Nginx域名重定向

配置方式

测试效果

Nginx访问日志

配置方式

测试效果

Nginx日志切割

自定义日志切割脚本

任务计划

静态文件:不记录日志,过期时间

配置方式

测试效果

Nginx防盗链

配置方式

测试效果

Nginx访问控制

配置方式

测试效果

匹配正则

根据user_agent限制

Nginx解析php相关配置

配置方式

测试效果

配置php-fpm监听 ip:port

Nginx代理

配置代理服务器之前的测试

配置代理服务器

测试效果

Nginx 中last和break 及 permanent 和 redirect 的爱恨情仇

rewrite中的break和last

常见的502错误

nginx location优先级


默认虚拟主机

配置方式

1:删除/usr/local/nginx/conf/nginx.conf文件中http{}配置里的server{} 
然后在http{}配置的最后添加一行:include vhost/*.conf

##最后/usr/local/nginx/conf/nginx.conf文件内容如下:
[root@server-lnmp ~]# cat /usr/local/nginx/conf/nginx.conf
user nobody nobody;
worker_processes 2;
error_log /usr/local/nginx/logs/nginx_error.log crit;
pid /usr/local/nginx/logs/nginx.pid;
worker_rlimit_nofile 51200;
events
{
    use epoll;
    worker_connections 6000;
}
http
{
    include mime.types;
    default_type application/octet-stream;
    server_names_hash_bucket_size 3526;
    server_names_hash_max_size 4096;
    log_format combined_realip '$remote_addr $http_x_forwarded_for [$time_local]'
    ' $host "$request_uri" $status'
    ' "$http_referer" "$http_user_agent"';
    sendfile on;
    tcp_nopush on;
    keepalive_timeout 30;
    client_header_timeout 3m;
    client_body_timeout 3m;
    send_timeout 3m;
    connection_pool_size 256;
    client_header_buffer_size 1k;
    large_client_header_buffers 8 4k;
    request_pool_size 4k;
    output_buffers 4 32k;
    postpone_output 1460;
    client_max_body_size 10m;
    client_body_buffer_size 256k;
    client_body_temp_path /usr/local/nginx/client_body_temp;
    proxy_temp_path /usr/local/nginx/proxy_temp;
    fastcgi_temp_path /usr/local/nginx/fastcgi_temp;
    fastcgi_intercept_errors on;
    tcp_nodelay on;
    gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 8k;
    gzip_comp_level 5;
    gzip_http_version 1.1;
    gzip_types text/plain application/x-javascript text/css text/htm 
    application/xml;
    include vhost/*.conf;  ##这一行是删除server{}标签以后添加的
}

##注意nginx配置文件中,一条配置必须以分号 ; 结束,否则都视为一条配置;

2:创建虚拟主机的配置文件存放目录vhost ,和虚拟主机配置文件

[root@server-lnmp ~]# mkdir /usr/local/nginx/conf/vhost
[root@server-lnmp ~]# ls -dl /usr/local/nginx/conf/vhost/
drwxr-xr-x. 2 root root 6 Jul  4 22:45 /usr/local/nginx/conf/vhost/

##创建虚拟主机配置文件,并写入配置内容
[root@server-lnmp ~]# vim /usr/local/nginx/conf/vhost/test.com.conf
[root@server-lnmp ~]# cat /usr/local/nginx/conf/vhost/test.com.conf 
server
{
    listen 80;
    server_name www.default.com default_server;
    index index.html index.htm index.php;
    root /data/wwwroot/www.default.com/;
}
server
{
    listen 80;
    server_name www.test.com test.com ;
    index index.html index.htm index.php;
    root /data/wwwroot/www.test.com/;

}

## 一个server{} 就是一个虚拟主机
## 可以在一个配置文件中写多个虚拟主机
## 也可以给每一个虚拟主机创建单独的配置文件
## nginx的server_name与apache不同,nginx可以直接定义多个server_name
## 当server_name后面带有default_server字段时,就代表这个虚拟主机就是默认虚拟主机
## 否则跟apache相同,第一个虚拟主机为默认虚拟主机

检查配置文件是否有语法错误,平滑重启nginx服务

##为了方便使用nginx命令,可以将/usr/local/nginx/sbin目录加入PATH环境变量
[root@server-lnmp ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' >> /etc/profile

##检查语法错误,最后显示ok和successful代表没有语法上的错误
[root@server-lnmp ~]# 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

##启动nginx服务,直接执行nginx命令即可
##平滑重启nginx服务,代表在不停止nginx服务的情况下,重新加载配置文件,重启工作线程
[root@server-lnmp ~]# nginx -s reload

.

测试访问

在/data/wwwroot/目录下创建虚拟主机的根目录一个测试页文件

[root@server-lnmp ~]# mkdir -p /data/wwwroot/www.test.com
[root@server-lnmp ~]# mkdir -p /data/wwwroot/www.default.com/
[root@server-lnmp ~]# echo '<h1>This is test page</h1>' > /data/wwwroot/www.test.com/index.html
[root@server-lnmp ~]# echo '<h1>This is defalut site</h1>' > /data/wwwroot/www.default.com/index.html

使用curl测试访问www.test.com

[root@server-lnmp ~]# curl -x127.0.0.1:80 www.test.com
<h1>This is test page</h1>

使用curl测试访问www.default.com

[root@server-lnmp ~]# curl -x10.1.1.28:80 www.default.com
<h1>This is defalut site</h1>
  •  

使用curl测试访问其他没有定义过server_name的域名

[root@server-lnmp ~]# curl -x10.1.1.28:80 www.aaa.com
<h1>This is defalut site</h1>
[root@server-lnmp ~]# curl -x10.1.1.28:80 bbb.cn
<h1>This is defalut site</h1>

Nginx用户认证

配置方式

在server_name 是www.test.com的虚拟主机配置下面添加以下的配置

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

查看添加配置后的文件内容

[root@server-lnmp ~]# vim /usr/local/nginx/conf/vhost/test.com.conf 
[root@server-lnmp ~]# cat !$
cat /usr/local/nginx/conf/vhost/test.com.conf
server
{
    listen 80;
    server_name www.default.com default_server;
    index index.html index.htm index.php;
    root /data/wwwroot/www.default.com/;
}
server
{
    listen 80;
    server_name www.test.com test.com ;
    index index.html index.htm index.php;
    root /data/wwwroot/www.test.com/;

    auth_basic              "Auth";
    auth_basic_user_file    /usr/local/nginx/conf/htpasswd;  # 用户密码文件 
    }
}

##注意auth_basic_user_file 的路径一定要填正确,否则报403错误

生成用于验证的用户和密码 
这里也需要用到apache的htpasswd命令 
如果没有这个命令可以yum安装httpd-tools可以了

[root@server-lnmp ~]# yum install -y httpd-tools
[root@server-lnmp ~]# htpasswd -c /usr/local/nginx/conf/htpasswd testuser
New password: 
Re-type new password: 
Adding password for user testuser
#注:htpasswd命令的-c选项,只有在第一次创建用户认证的密码文件时需要使用, 
#   如果再次添加用户和密码时使用了-c选项,则会覆盖掉之前的所有内容

检查语法错误,重载配置文件

[root@server-lnmp ~]# 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@server-lnmp ~]# nginx -s reload

测试效果

curl 测试访问www.test.com

[root@server-lnmp ~]# curl -I -x10.1.1.28:80 www.test.com
HTTP/1.1 401 Unauthorized
#状态码为401,说明需要认证才能访问

curl 测试用户认证访问

[root@server-lnmp ~]# curl  -utestuser:123456 -x10.1.1.28:80 www.test.com
<h1>This is test page</h1>

针对目录的用户认证

修改test.com.conf配置文件

[root@server-lnmp ~]# vim /usr/local/nginx/conf/vhost/test.com.conf 
[root@server-lnmp ~]# cat /usr/local/nginx/conf/vhost/test.com.conf 
server
{
    listen 80;
    server_name www.default.com default_server;
    index index.html index.htm index.php;
    root /data/wwwroot/www.default.com/;
}
server
{
    listen 80;
    server_name www.test.com test.com ;
    index index.html index.htm index.php;
    root /data/wwwroot/www.test.com/;

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


#注意location匹配的目录不再是根目录,而是/admin/目录
#这里的根目录指的是网站的根目录:/data/wwwroot/www.test.com/

#修改完检测语法,重载配置文件
[root@server-lnmp ~]# 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@server-lnmp ~]# nginx -s reload

测试效果

创建/data/wwwroot/www.test.com/admin目录

[root@server-lnmp ~]# mkdir /data/wwwroot/www.test.com/admin

curl测试访问www.test.com

[root@server-lnmp ~]# curl -I -x10.1.1.28:80 www.test.com
HTTP/1.1 200 OK
#状态码200 访问正常

curl测试访问www.test.com/admin

[root@server-lnmp ~]# curl -I -x10.1.1.28:80 www.test.com/admin/
HTTP/1.1 401 Unauthorized

#即使访问请求的文件并不存在也需要验证
[root@server-lnmp ~]# curl -I -x10.1.1.28:80 www.test.com/admin/fasd
HTTP/1.1 401 Unauthorized

针对文件的用户认证

修改test.com.conf配置文件

[root@server-lnmp ~]# vim /usr/local/nginx/conf/vhost/test.com.conf 
[root@server-lnmp ~]# cat /usr/local/nginx/conf/vhost/test.com.conf 
server
{
    listen 80;
    server_name www.default.com default_server;
    index index.html index.htm index.php;
    root /data/wwwroot/www.default.com/;
}
server
{
    listen 80;
    server_name www.test.com test.com ;
    index index.html index.htm index.php;
    root /data/wwwroot/www.test.com/;

    location ~ ^.*/admin.html
    {
    auth_basic              "Auth";
    auth_basic_user_file    /usr/local/nginx/conf/htpasswd;
    }
}

##注意location
##修改完检查语法,重载配置文件

测试效果

创建测试文件

[root@server-lnmp ~]# echo '/data/wwwroot/www.test.com/admin.html' >/data/wwwroot/www.test.com/admin.html
[root@server-lnmp ~]# echo '/data/wwwroot/www.test.com/admin/admin.html' >/data/wwwroot/www.test.com/admin/admin.html

curl测试访问www.test.com/admin.html

[root@server-lnmp ~]# curl -I -x10.1.1.28:80 www.test.com/admin.html
HTTP/1.1 401 Unauthorized

curl测试访问www.test.com

[root@server-lnmp ~]# curl -I -x10.1.1.28:80 www.test.com
HTTP/1.1 200 OK

curl测试访问www.test.com/admin/admin.html

[root@server-lnmp ~]# curl -I -x10.1.1.28:80 www.test.com/admin/admin.html
HTTP/1.1 401 Unauthorized

Nginx域名重定向

配置方式

修改test.com.conf配置文件

[root@server-lnmp ~]# vim /usr/local/nginx/conf/vhost/test.com.conf 
[root@server-lnmp ~]# cat /usr/local/nginx/conf/vhost/test.com.conf 
server
{
    listen 80;
    server_name www.default.com default_server;
    index index.html index.htm index.php;
    root /data/wwwroot/www.default.com/;
}
server
{
    listen 80;
    server_name www.test.com test.com abc.com;
    index index.html index.htm index.php;
    root /data/wwwroot/www.test.com/; #网站域名
    if ($host != 'www.test.com' ) {
        rewrite  ^/(.*)$  http://test.com/$1  permanent;
    }

    location ~ ^.*/admin.html
    {
    auth_basic              "Auth";
    auth_basic_user_file    /usr/local/nginx/conf/htpasswd;
    }
}

配置解释

#下面的就是域名重定向的配置
    if ($host != 'www.test.com' ) {
        rewrite  ^/(.*)$  http://www.test.com/$1  permanent;
    }

#在nginx配置文件中可以使用if判断
#这个配置的大概意思是当 $host 不是www.test.com的时候
#执行rewrite 将域名重定向到http://www.test.com
#$host就是访问请求的域名,也就是server_name

# ^/(.*)$  这个可以匹配出域名后面的URI地址,
# $1 就是调用前面(.*)匹配到的URI,类似sed 这样就可以进行更精确的重定向了。

#最后的 permanent 表示的是永久重定向 状态码为 301
#如果改为 redirect 表示临时重定向,状态码302

关于URI

在nginx中有几个关于uri的变量,包括$uri $request_uri $document_uri $args,
下面看一下他们的区别 :
假如访问的URL为:http://www.test.com/index.php?a=1&b=2
$uri==/index.php
$request_uri==/index.php?a=1&b=2
$document_uri==/index.php
$args==?a=1&b=2

##一般uri和document_uri是相同的

测试效果

curl测试访问test.com和abc.com

[root@server-lnmp ~]# curl -I -x10.1.1.28:80 test.com
HTTP/1.1 301 Moved Permanently
Server: nginx/1.12.1
Date: Thu, 05 Jul 2018 11:34:22 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: http://www.test.com/

[root@server-lnmp ~]# curl -I -x10.1.1.28:80 abc.com/jfkdsa/gfda
HTTP/1.1 301 Moved Permanently
Server: nginx/1.12.1
Date: Thu, 05 Jul 2018 11:34:58 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: http://www.test.com/jfkdsa/gfda

[root@server-lnmp ~]# curl -I -x10.1.1.28:80 www.test.com
HTTP/1.1 200 OK
#只有访问www.test.com不会重定向

Nginx访问日志

配置方式

Nginx默认的日志格式

[root@server-lnmp conf]# grep -A2 'log_format' nginx.conf
    log_format combined_realip '$remote_addr $http_x_forwarded_for [$time_local]'
    ' $host "$request_uri" $status'
    ' "$http_referer" "$http_user_agent"';
#上面grep筛选出来的内容就是是日志文件的格式,
#也可以自行调整各个变量的位置
#他们分别代表的含义如下:
log_format              #定义日志格式的函数
combined_realip         #定义日志格式名称,可随意设定
$remote_addr            #客户端的公网IP
$http_x_forwarded_for   #代理服务器的IP
$time_local             #服务器本地时间
$host                   #访问主机名(域名,网址)
$request_uri            #访问的URI地址
$status                 #状态码
$http_referer           #referer
$http_user_agent        #user_agent

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

[root@server-lnmp conf]# cd /usr/local/nginx/conf/
[root@server-lnmp conf]# vim vhost/test.com.conf 
[root@server-lnmp conf]# cat vhost/test.com.conf 
server
{
    listen 80;
    server_name www.default.com default_server;
    index index.html index.htm index.php;
    root /data/wwwroot/www.default.com/;
}
server
{
    listen 80;
    server_name www.test.com test.com abc.com;
    index index.html index.htm index.php;
    root /data/wwwroot/www.test.com/;
    if ($host != 'www.test.com') {
        rewrite ^/(.*)$ http://www.test.com/$1 permanent; 
    }
    location ~ ^.*/admin.html
    {
    auth_basic              "Auth";
    auth_basic_user_file    /usr/local/nginx/conf/htpasswd;
    }
    access_log logs/test_access.log combined_realip;   
}

配置添加完成后-t测试语法错误,重载配置文件

配置文件的内容最后一行内容就是定义虚拟主机的访问日志

access_log logs/test_access.log combined_realip;

#access_log            #定义访问日志功能
#logs/test_access.log  #定义访问日志文件的存放路径
#combined_realip       #指定nginx.conf文件中定义的日志格式名称

测试效果

使用curl访问一次www.test.com,然后查看日志文件的内容。

[root@server-lnmp conf]# curl -x10.1.1.28:80 www.test.com
<h1>This is test page</h1>

[root@server-lnmp conf]# cat /usr/local/nginx/logs/www_test_com.log 
10.1.1.28 - [05/Jul/2018:20:36:54 +0800] www.test.com "/" 200 "-" "curl/7.29.0"

Nginx日志切割

nginx和apache不同,nginx没有自带的日志切割工具 
所以需要自己编写一个日志切割脚本, 
然后配合计划任务来实现日志切割的功能。

自定义日志切割脚本

脚本内容如下,一般脚本都放在/usr/local/sbin/目录下

[root@server-lnmp conf]# vim /usr/local/sbin/nginx_log_rotate.sh
[root@server-lnmp conf]# cat /usr/local/sbin/nginx_log_rotate.sh
#! /bin/bash
## 假设nginx的日志存放路径为/usr/local/nginx/logs/
d=`date -d "-1 day" +%Y%m%d` 
logdir="/usr/local/nginx/logs"
nginx_pid="/usr/local/nginx/logs/nginx.pid"
cd $logdir
for log in `ls *.log`
do
    mv $log $log-$d
    find -mtime +30 -type f -name "*.log" -exec rm -f {} \;
done
/bin/kill -HUP `cat $nginx_pid`

任务计划

编写完日志切割脚本后,使用crontab -e添加一条任务计划 
每天0点0分执行这个日志切割脚本

[root@server-lnmp conf]# crontab -e
no crontab for root - using an empty one
crontab: installing new crontab
[root@server-lnmp conf]# crontab -l
0 0 * * * /bin/bash /usr/local/sbin/nginx_log_rotate.sh

静态文件:不记录日志,过期时间

配置方式

编辑虚拟主机配置文件, 
在虚拟主机www.test.com的配置中添加以下内容

    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$  
        {
              expires      7d;
              access_log off;
        }
    location ~ .*\.(js|css)$
        {
              expires      12h;
              access_log off;
        }

##添加完检测语法,重载配置。

配置说明:

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$  
#表示location匹配URI以gif、jpg、png、bmp、swf结尾的访问请求

#当有匹配到相关的访问请求时,
    expires      7d;
        #设定文件缓存到浏览器的过期时间7天。
        #Nd=N天,
        #Nh=N小时
        #Nm=N分钟
        #Ns=N秒    

    access_log off;
        #关闭日志记录 

修改配置后的test.com.conf文件的内容如下

server
{
    listen 80;
    server_name www.default.com default_server;
    index index.html index.htm index.php;
    root /data/wwwroot/www.default.com/;
}
server
{
    listen 80;
    server_name www.test.com test.com abc.com;
    index index.html index.htm index.php;
    root /data/wwwroot/www.test.com/;
    if ($host != 'www.test.com') {
        rewrite ^/(.*)$ http://www.test.com/$1 permanent; 
    }
    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$  
        {
              expires      7d;
              access_log off;
        }
    location ~ .*\.(js|css)$
        {
              expires      12h;
              access_log off;
        }
    location ~ ^.*/admin.html
    {
    auth_basic              "Auth";
    auth_basic_user_file    /usr/local/nginx/conf/htpasswd;
    }
    access_log logs/www_test_com.log combined_realip;
}

测试效果

在/data/wwwroot/www.test.com/目录下创建两个相关的测试文件

[root@server-lnmp conf]# echo 'test.jpg' > /data/wwwroot/www.test.com/test.jpg
[root@server-lnmp conf]# echo 'test.css' > /data/wwwroot/www.test.com/test.css

curl测试访问www.test.com/test.jpg 和 www.test.com/test.css

[root@server-lnmp conf]# curl -x127.0.0.1:80 www.test.com/test.jpg
test.jpg

[root@server-lnmp conf]# curl -x127.0.0.1:80 www.test.com/test.jpg -I
HTTP/1.1 200 OK
(省略...)
Cache-Control: max-age=604800   #这个字段就表示缓存的过期时间
Accept-Ranges: bytes

[root@server-lnmp conf]# curl -x127.0.0.1:80 www.test.com/test.css
test.css

[root@server-lnmp conf]# curl -x127.0.0.1:80 www.test.com/test.css -I
HTTP/1.1 200 OK
(省略...)
Cache-Control: max-age=43200
Accept-Ranges: bytes

[root@server-lnmp conf]# curl -x127.0.0.1:80 www.test.com/index.html
<h1>This is test page</h1>
#最后访问一次index.html

查看访问日志

[root@server-lnmp conf]# cat /usr/local/nginx/logs/www_test_com.log 
10.1.1.28 - [05/Jul/2018:20:36:54 +0800] www.test.com "/" 200 "-" "curl/7.29.0"
127.0.0.1 - [05/Jul/2018:21:31:25 +0800] www.test.com "/index.html" 200 "-" "curl/7.29.0"

##可以看到没有访问test.jpg和test.css的访问纪律

Nginx防盗链

配置方式

防盗链可以和静态文件结合起来配置。 
需要修改前面添加的静态文件的配置、

修改后test.com.conf文件的内容如下:

[root@server-lnmp conf]# cat !$
cat vhost/test.com.conf
server
{
    listen 80;
    server_name www.default.com default_server;
    index index.html index.htm index.php;
    root /data/wwwroot/www.default.com/;
}
server
{
    listen 80;
    server_name www.test.com test.com abc.com;
    index index.html index.htm index.php;
    root /data/wwwroot/www.test.com/;
    if ($host != 'www.test.com') {
        rewrite ^/(.*)$ http://www.test.com/$1 permanent; 
    }
    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 ;
        if ($invalid_referer) {
        return 403;
        }
        access_log off;
    }

    location ~ .*\.(js|css)$
        {
              expires      12h;
              access_log off;
        }
    location ~ ^.*/admin.html
    {
    auth_basic              "Auth";
    auth_basic_user_file    /usr/local/nginx/conf/htpasswd;
    }
    access_log logs/www_test_com.log combined_realip;
}

防盗链配置解释

    valid_referers none blocked server_names  *.test.com ;
    if ($invalid_referer) {
        return 403;
    }

    #valid_referers 配置referer白名单
    #none 代表没有referer
    #blocked 代表有referer但是被防火墙或者是代理给去除了
    #server_names 代表这个虚拟主机的所有server_name
    #*.test.com  #这个可以是正则匹配的字段, 或者指定的域名

#当访问请求不包含在白名单里面时:
#invalid_referer的值为 1 ,就会执行if语句,

#当访问请求包含在白名单里面时,
#invalid_referer的值为 0 就不会执行 if 语句

测试效果

curl直接请求访问www.test.com/test.jpg 
这时referer为none 所有可以访问

[root@server-lnmp conf]# curl -I -x127.0.0.1:80 www.test.com/test.jpg
HTTP/1.1 200 OK

curl 指定referer为http://baidu.com 进行访问请求 
这时referer为http://baidu.com 没在白名单里面, 
所以状态码返回403,拒绝访问了

[root@server-lnmp conf]# curl -I -e "http://baidu.com" -x127.0.0.1:80 www.test.com/test.jpg
HTTP/1.1 403 Forbidden

Nginx访问控制

配置方式

需求:访问/aaa/目录的请求,只允许某几个IP访问,

在虚拟主机www.test.com的配置里添加如下内容:

    location /aaa/
    {
        allow 127.0.0.1;
        deny all;
    }

配置完检查语法,重载配置

[root@server-lnmp conf]# rnginx 
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@server-lnmp conf]# which rnginx
alias rnginx='/usr/local/nginx/sbin/nginx -t && /usr/local/nginx/sbin/nginx -s reload'
        /usr/local/nginx/sbin/nginx
        /usr/local/nginx/sbin/nginx

配置说明:

allow 127.0.0.1;   #规则,允许ip 127.0.0.1访问,这里的ip就是访问日志里的$remote_addr 
deny all;          #规则,拒绝所有

#也可以配置为allow all;然后deny某些ip
#匹配规则是从上往下匹配,当匹配到一个规则就不再往下匹配了

测试效果

创建测试目录和文件

[root@server-lnmp conf]# mkdir /data/wwwroot/www.test.com/aaa
[root@server-lnmp conf]# echo 'aaa test' > /data/wwwroot/www.test.com/aaa/index.html

curl 将域名www.test.com/aaa/解析到127.0.0.1:80

这时系统本地就会使用127.0.0.1这个ip向nginx服务发起访问请求,

所以remote_addr就是127.0.0.1,可以正常访问

[root@server-lnmp conf]# curl -x127.0.0.1:80 www.test.com/aaa/index.html
aaa test

curl 将域名www.test.com/aaa/解析到10.1.1.28:80

这时系统本地就会使用10.1.1.28这个ip向nginx服务发起访问请求,

所以remote_addr就是10.1.1.28,会拒绝访问

[root@server-lnmp conf]# curl -x10.1.1.28:80 www.test.com/aaa/index.html
<html>
<head><title>403 Forbidden</title></head>
<body bgcolor="white">
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.12.1</center>
</body>
</html>

匹配正则

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

##这样可以拒绝所有abc目录下或者image目录下以.php结尾文件的访问请求

根据user_agent限制

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

#如此可以拒绝所有user_agent为Spider/3.0、YoudaoBot、Tomato的访问请求
#deny all和return 403效果一样

Nginx解析php相关配置

配置方式

在虚拟主机www.test.com 的配置最后面的access_log前一行添加下面的内容

    location ~ \.php$
        {
            include fastcgi_params;
            fastcgi_pass unix:/tmp/php-fcgi.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME /data/wwwroot/test.com$fastcgi_script_name;
        }

##配置添加完成先不要重载配置文件

配置解释:

location ~ \.php$     #location匹配所有document_uri以 .php 结尾的访问请求
    {
        include fastcgi_params;    
            #引用fastcgi_params常量文件           

        fastcgi_pass unix:/tmp/php-fcgi.sock;  
            #指定PHP的sock文件路径,
            #如果php-fpm.conf配置listen是ip:port,这里也需要配置为相同的ip:port
            #这里配置错误会出现502报错

        fastcgi_index index.php;   
            #指定php的索引页

        fastcgi_param SCRIPT_FILENAME /data/wwwroot/test.com$fastcgi_script_name; 
            #指定PHP程序的请求路径,  $ 符号前面的路径需要和虚拟主机的root路径相同
            #这个路径有问题会出现404报错
    }

测试效果

创建测试的php文件

[root@server-lnmp conf]# echo -e "<?php\necho 'PHP test page';" > /data/wwwroot/www.test.com/test.php

在没有重载配置的情况下,先测试访问www.test.com/test.php

结果输出的是php的源代码,表示没有解析PHP

[root@server-lnmp conf]# curl -x10.1.1.28:80 www.test.com/test.php
<?php
echo 'PHP test page';

重载nginx配置文件后再次访问www.test.com/test.php

输出结果为PHP test page 表示成功解析了PHP脚本

[root@server-lnmp conf]# curl -x10.1.1.28:80 www.test.com/test.php
PHP test page

如果SCRIPT_FILENAME填写有误就会输出File not found,

获取头部信息状态码为404

[root@server-lnmp conf]# curl -x10.1.1.28:80 www.test.com/test.php
File not found.

[root@server-lnmp conf]# curl -I -x10.1.1.28:80 www.test.com/test.php
HTTP/1.1 404 Not Found

如果fastcgi_pass 填写有误会出现502报错

[root@server-lnmp conf]# curl -I -x10.1.1.28:80 www.test.com/test.php
HTTP/1.1 502 Bad Gateway

配置php-fpm监听 ip:port

修改/usr/local/php-fpm/etc/php-fpm.conf配置文件:

将listen = /tmp/php-fcgi.sock 修改为 listen = 10.1.1.28:9000 ,这里的ip需要根据自己的环境来填写

[root@server-lnmp conf]# vim /usr/local/php-fpm/etc/php-fpm.conf
[root@server-lnmp conf]# grep '^listen = ' /usr/local/php-fpm/etc/php-fpm.conf
  listen = 10.1.1.28:9000

再修改test.com.conf中虚拟主机www.test.com的配置

将fastcgi_pass unix:/tmp/php-fcgi.sock; 修改为fastcgi_pass 10.1.1.2:9000;

[root@server-lnmp conf]# vim vhost/test.com.conf 
[root@server-lnmp conf]# grep 'fastcgi_pass'  vhost/test.com.conf 
        fastcgi_pass 10.1.1.28:9000;

重载php-fpm和nginx配置

[root@server-lnmp conf]# /etc/init.d/php-fpm reload
Reload service php-fpm  done

[root@server-lnmp conf]# rnginx 
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@server-lnmp conf]# which rnginx
alias rnginx='/usr/local/nginx/sbin/nginx -t && /usr/local/nginx/sbin/nginx -s reload'
        /usr/local/nginx/sbin/nginx
        /usr/local/nginx/sbin/nginx

测试访问www.test.com/test.php

[root@server-lnmp conf]# curl -x10.1.1.28:80 www.test.com/test.php
PHP test page

Nginx代理

配置代理服务器之前的测试

#没配置代理前将www.baidu.com解析到127.0.0.1
#结果只是访问了默认虚拟主机
[root@server-lnmp conf]# curl -x127.0.0.1:80 www.baidu.com
<h1>This is defalut site</h1>
[root@server-lnmp conf]# curl -x127.0.0.1:80 www.baidu.com -I
HTTP/1.1 200 OK
Server: nginx/1.12.1
Date: Thu, 05 Jul 2018 17:19:51 GMT
Content-Type: text/html
Content-Length: 30
Last-Modified: Wed, 04 Jul 2018 15:41:04 GMT
Connection: keep-alive
ETag: "5b3cea90-1e"
Accept-Ranges: bytes

配置代理服务器

这里我们先用ping命令查看一下baidu.com的ip地址

[root@server-lnmp conf]# ping www.baidu.com -c1
PING www.a.shifen.com (180.97.33.107) 56(84) bytes of data.
64 bytes from 180.97.33.107 (180.97.33.107): icmp_seq=1 ttl=54 time=32.3 ms

#可以看到百度的IP为 180.97.33.107

在/usr/local/nginx/conf/vhost/目录下添加一个配置文件 proxy.conf

并写入代理服务器的配置

[root@server-lnmp conf]# vim /usr/local/nginx/conf/vhost/proxy.conf 
[root@server-lnmp conf]# cat /usr/local/nginx/conf/vhost/proxy.conf
server
{
    listen 80;
    server_name www.baidu.com;         #这里写代理服务器的域名

    location /
    {
        proxy_pass      http://180.97.33.107/;  #这里的IP写web服务的ip
        proxy_set_header Host   $host;          #设定header信息的Host变量
        proxy_set_header X-Real-IP      $remote_addr;  #设定header信息的remote_addr变量
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #设定header信息的X-Forwarded-For变量
    }
}

#复制的最好将注释删掉
#配置完成检查语法,重载nginx配置

测试效果

再次测试访问 curl -x127.0.0.1:80 www.baidu.com

将www.baidu.com解析到本机,结果可以访问到真正的百度首页了

[root@server-lnmp conf]# curl -x127.0.0.1:80 www.baidu.com
<!DOCTYPE html>
<!--STATUS OK--><html> 
(省略...)
使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>

[root@server-lnmp conf]# curl -x127.0.0.1:80 www.baidu.com -I
HTTP/1.1 200 OK
Server: nginx/1.12.1
Date: Thu, 05 Jul 2018 18:25:24 GMT
Content-Type: text/html
Content-Length: 277
Connection: keep-alive
Accept-Ranges: bytes
Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform
Etag: "575e1f74-115"
Last-Modified: Mon, 13 Jun 2016 02:50:28 GMT
Pragma: no-cache

 http://blog.51cto.com/unixman/1711943

Nginx 中last和break 及 permanent 和 redirect 的爱恨情仇

一、last 和 break 总结如下:

(1)、last 和 break 当出现在location 之外时,两者的作用是一致的没有任何差异。

注意一点就是,他们会跳过所有的在他们之后的rewrite 模块中的指令,去选择自己匹配的location

Example:

<span style="color:#333333"><span style="color:black"><code class="language-python">rewrite url1 url2 last<span style="color:#999999">;</span> ①
rewrite url3 url4 last<span style="color:#999999">;</span> ②
rewrite url5 url6 last<span style="color:#999999">;</span> ③

location <span style="color:#9a6e3a">~</span>  url2     ④
location <span style="color:#9a6e3a">~</span>  url4     ⑤
location <span style="color:#9a6e3a">~</span>  url6     ⑥</code></span></span>

当① 这条rewrite 规则生效后,它后面的②和③ 将被跳过不做判断,而去直接选择 后面的location。

这里可能有一个疑问,那些指令输入rewrite 模块中的指令呢? 若是使用nginx本身,你就要到官网上去查询了。

但如果你使用的是tengine ,可以使用tengine -V 。会将你想要的信息列举出来。

(1)、last 和 break 当出现在location 内部时,两者就存在了差异。

   last: 使用了last 指令,rewrite 后会跳出location 作用域,重新开始再走一次刚刚的行为

   break: 使用了break 指令,rewrite后不会跳出location 作用域。它的生命也在这个location中         终结。

Example:

<span style="color:#333333"><span style="color:black"><code class="language-python">rewrite xxx1 yyy last<span style="color:#999999">;</span> ⑦
rewrite xxx2 yyy last<span style="color:#999999">;</span> ⑧
rewrite xxx3 yyy last<span style="color:#999999">;</span> ⑨
rewrite xxx4 yyy last<span style="color:#999999">;</span> ⑩

location <span style="color:#9a6e3a">~</span>  url1
<span style="color:#999999">{</span>
    rewrite url1 url2 last<span style="color:#999999">;</span> ①
<span style="color:#999999">}</span>

location <span style="color:#9a6e3a">~</span>  url2
<span style="color:#999999">{</span>
    rewrite url3 url4 <span style="color:#0077aa">break</span><span style="color:#999999">;</span> ②
    fastcgi_pass <span style="color:#990055">127.0</span><span style="color:#990055">.0</span><span style="color:#990055">.1</span><span style="color:#999999">:</span><span style="color:#990055">9000</span><span style="color:#999999">;</span>
<span style="color:#999999">}</span></code></span></span>

以上事例:

第一个location 中的 rewrite 指令处理完成之后,会跳出location ,再重新判断rewrite 7 ~ 9 的规则。

第二个location 中的 rewrite  指令处理完成之后,不会跳出location, 更不会重新判断rewrite 7 ~ 9 的规则。而只能将

信息传递给后面的fastcgi_pass 或者proxy_pass 等指令

二、permanent 和 redirect 总结如下:

permanent: 大家公认的信息 ,永久性重定向。请求日志中的状态码为301

redirect: 大家公认的信息 ,临时重定向。请求日志中的状态码为302

从实现功能的角度上去看,permanent 和 redirect 是一样的。不存在哪里好,哪里坏。也不存在什么性能上的问题。

但从SEO(或者是百度爬你的网站时)。 类似于这样的东西,会对你到底是永久性重定向还是临时重定向感兴趣。了解不到,需要深入,就google 吧。

三、last 和 break VS permanent 和 redirect 

在 permanent 和 redirect  中提到了 状态码 301 和 302。 那么last 和 break 想对于的访问日志的请求状态码又是多少呢?

答案为: 200

这两类关键字,我们能够眼睛看到的差异是什么呢? 我举个例子说明吧:

当你打开一个网页,同时打开debug 模式时,会发现301 和 302 时的行为是这样的。第一个请求301 或者 302 后,浏览器重新获取了一个新的URL ,然后会对这个新的URL 重新进行访问。所以当你配置的是permanent 和 redirect ,你对一个URL 的访问请求,落到服务器上至少为2次。

而当你配置了last 或者是break 时,你最终的URL 确定下来后,不会将这个URL返回给浏览器,而是将其扔给了fastcgi_pass或者是proxy_pass指令去处理。请求一个URL ,落到服务器上的次数就为1次。

rewrite/break.md - master - 代码浏览 - nginx - aminglinux  https://coding.net/u/aminglinux/p/nginx/git/blob/master/rewrite/break.md#user-content-rewrite¦ᄌᆳ￧レトbreak¥メフlast

rewrite中的break和last

两个指令用法相同,但含义不同,需要放到rewrite规则的末尾,用来控制重写后的链接是否继续被nginx配置执行(主要是rewrite、return指令)。

示例1(连续两条rewrite规则):
server{
    listen 80; 
    server_name test.com;
    root /tmp/123.com;

    rewrite /1.html /2.html ;
    rewrite /2.html /3.html ;
    
}
当我们请求1.html时,最终访问到的是3.html,两条rewrite规则先后执行。

break和last在location {}外部

格式:rewrite xxxxx  break;

示例2(增加break):
server{
    listen 80; 
    server_name test.com;
    root /tmp/123.com;

    rewrite /1.html /2.html break;
    rewrite /2.html /3.html;
}
当我们请求1.html时,最终访问到的是2.html
说明break在此示例中,作用是不再执行break以下的rewrite规则。

但,当配置文件中有location时,它还会去执行location{}段的配置(请求要匹配该location)。

示例3(break后面还有location段):
server{
    listen 80; 
    server_name test.com;
    root /tmp/123.com;

    rewrite /1.html /2.html break;
    rewrite /2.html /3.html;
    location /2.html {
        return 403;
    }
}
当请求1.html时,最终会返回403状态码,说明它去匹配了break后面的location{}配置。

以上2个示例中,可以把break替换为last,它们两者起到的效果一模一样。

当break和last在location{}里面

示例4(什么都不加):
server{
    listen 80; 
    server_name test.com;
    root /tmp/123.com;
    
    location / {
        rewrite /1.html /2.html;
        rewrite /2.html /3.html;
    }
    location /2.html
    {
        rewrite /2.html /a.html;
    }
    location /3.html
    {
        rewrite /3.html /b.html;
    }
}
当请求/1.html,最终将会访问/b.html,连续执行location /下的两次rewrite,跳转到了/3.html,然后又匹配location /3.html

示例5(增加break):
server{
    listen 80; 
    server_name test.com;
    root /tmp/123.com;
    
    location / {
        rewrite /1.html /2.html break;
        rewrite /2.html /3.html;
    }
    location /2.html
    {
        rewrite /2.html /a.html;
    }
    location /3.html
    {
        rewrite /3.html /b.html;
    }
}
当请求/1.html,最终会访问/2.html
在location{}内部,遇到break,本location{}内以及后面的所有location{}内的所有指令都不再执行。


示例6(增加last):
server{
    listen 80; 
    server_name test.com;
    root /tmp/123.com;
    
    location / {
        rewrite /1.html /2.html last;
        rewrite /2.html /3.html;
    }
    location /2.html
    {
        rewrite /2.html /a.html;
    }
    location /3.html
    {
        rewrite /3.html /b.html;
    }
}
当请求/1.html,最终会访问/a.html
在location{}内部,遇到last,本location{}内后续指令不再执行,而重写后的url再次从头开始,从头到尾匹配一遍规则。

常见的502错误 - 猿课论坛  http://ask.apelearn.com/question/9109

常见的502错误

常见的502错误
1.配置错误
因为nginx找不到php-fpm了,所以报错,一般是fastcgi_pass后面的路径配置错误了,后面可以是socket或者是ip:port


2.资源耗尽
lnmp架构在处理php时,nginx直接调取后端的php-fpm服务,如果nginx的请求量偏高,我们又没有给php-fpm配置足够的子进程,那么php-fpm就会资源耗尽,一旦资源耗尽nginx找不到php-fpm就会出现502错误,

解决方案
去调整php-fpm.conf中的pm.max_children数值,使其增加,但是也不能无限增加,毕竟资源有限,一般4G内存机器如果跑php-fpm和nginx,不跑mysql可以设置为150,8G为300以此类推


3.除了上面的两种错误还有其他的原因,很少有,我们可以借助nginx的错误日志来进行排查vim /usr/local/nginx/logs/nginx_error.log  我们也可以给日志定义级别vim/usr/local/nginx/conf/nginx.conf 找到error_log,默认是crit最严谨的就行,也可以改成debug显示的信息最全面,但是很容易撑爆我们的磁盘。



首先我们需要让浏览器进行访问
修改nginx的配置文件
[root@wqslinux ~]# vim/usr/local/nginx/conf/vhosts/111.conf

server
{
   listen 80;
   server_name www.111.com;       //域名地址
   index index.html index.htm index.php;
   root /data/www/;

   location ~ \.php$ {
       include fastcgi_params;
       fastcgi_pass unix:/tmp/www.sock;  //修改sock
      #fastcgi_pass 127.0.0.1:9000;
       fastcgi_index index.php;
       fastcgi_param SCRIPT_FILENAME /data/www$fastcgi_script_name;
    }

}



检查语法是否正常
[root@wqslinux ~]#/usr/local/nginx/sbin/nginx -t
重新加载配置文件
[root@wqslinux ~]# /usr/local/nginx/sbin/nginx-s reload
[root@wqslinux ~]# /etc/init.d/nginx reload

检查nginx是那个用户跑的
[root@wqslinux ~]# ps aux |grep nginx
编辑php-fpm文件
我们要在这个php-fpm文件里面设置nginx的用户主,跟组这样才不会显示502
[root@wqslinux ~]# vim/usr/local/php/etc/php-fpm.conf

[global]
pid = /usr/local/php/var/run/php-fpm.pid
error_log =/usr/local/php/var/log/php-fpm.log
[www]
listen = /tmp/www.sock
user = php-fpm
group = php-fpm
listen.owner = nobody    //定义属主
listen.group = nobody    //定义属组
pm = dynamic
pm.max_children = 50
pm.start_servers = 20
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500
rlimit_files = 1024

配置完之后重启php-fpm
[root@wqslinux ~]# /etc/init.d/php-fpm restart
ps: 再补充一个,是近期很多同学遇到的问题
这种情况下,使用的是socket,版本高于5.4(含5.4) 默认监听的socket文件权限是所有者只读,属组和其他用户没有任何权限。所以,nginx的启动用户(咱们配置的是nobody)就没有办法去读这个socket文件,最终导致502,这个问题可以在nginx的错误日志中发现。解决办法很简单,上面给出的配置文件中就有避免这个问题的配置。
listen.owner = nobody    //定义属主
listen.group = nobody    //定义属组
这两个配置就是定义socket的属主和属组是谁。除了这个还有一种方法
listen.mode = 777
这样nobody也可以有读取权限了。

location/priority.md - master - 代码浏览 - nginx - aminglinux  https://coding.net/u/aminglinux/p/nginx/git/blob/master/location/priority.md

nginx location优先级

=  高于  ^~  高于  ~* 等于 ~  高于  /

对比/和~

示例1:
server{
    listen 80;
    server_name www.aminglinux.com;
    root /tmp/123.com;

    location /abc/
    {
        echo "/";
    }
    location ~ 'abc'
    {
        echo "~";
    }
}

测试命令:curl -x127.0.0.1:80 'www.aminglinux.com/abc/1.png'
结果是:~

对比~和~*

示例2:
server
{
    listen 80;
    server_name www.aminglinux.com;
    root /tmp/123.com;

    location ~ 'abc'
    {
        echo '~';
    }
    location ~* 'abc'
    {
        echo '~*';
    }
}
测试命令:curl -x127.0.0.1:80 'www.aminglinux.com/abc/123.html' 
结果是:~

示例3:
server
{
    listen 80;
    server_name www.aminglinux.com;
    root /tmp/123.com;

    location ~* 'abc'
    {
        echo '~*';
    }
    location ~ 'abc'
    {
        echo '~';
    }
}
测试命令:curl -x127.0.0.1:80 'www.aminglinux.com/abc/123.html' 
结果是:~*

结论:~和~*优先级其实是一样的,如果两个同时出现,配置文件中哪个location靠前,哪个生效。

对比^~和~

示例4:
server
{
    listen 80;
    server_name www.aminglinux.com;
    root /tmp/123.com;

    location ~ '/abc'
    {
        echo '~';
    }
    location ^~ '/abc'
    {
        echo '^~';
    }
}

测试命令:curl -x127.0.0.1:80 'www.aminglinux.com/abc/123.html
结果是:^~

对比=和^~

示例5:
server
{
    listen 80;
    server_name www.aminglinux.com;
    root /tmp/123.com;

    location ^~ '/abc.html'
    {
        echo '^~';
    }
    location = '/abc.html'
    {
        echo '=';
    }
}

测试命令:curl -x127.0.0.1:80 'www.aminglinux.com/abc.html
结果是:=

 

猜你喜欢

转载自blog.csdn.net/qq_42720896/article/details/82780399
今日推荐