12.7 Nginx默认虚拟主机
include vhost/*.conf;
记得加分号
vim conf www.aaa.conf
server
{
listen 80 default_server; // 有这个标记的就是默认虚拟主机
server_name aaa.com;
index index.html index.htm index.php;
root /data/wwwroot/default;
}
mkdir -p /data/wwwroot/default
cd !$
vim index.html
This is a default site
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload
12.8 Nginx用户认证
/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/wwwroot/test.com;
location /
{
auth_basic "Auth";
auth_basic_user_file /usr/local/nginx/conf/htpasswd;
}
}
测试返回401 需要认证
返回200状态码
针对目录做限制
location /admin
{
auth_basic "Auth";
auth_basic_user_file /usr/local/nginx/conf/htpasswd;
}
匹配一个url
location ~ admin.php
{
auth_basic "Auth";
auth_basic_user_file /usr/local/nginx/conf/htpasswd;
}
12.9 Nginx域名重定向
vim test.com.conf
server
{
listen 80;
server_name test.com test2.com;
index index.html index.htm index.php;
root /data/wwwroot/test.com;
if ($host != 'test.com' ) {
rewrite ^/(.*)$ http://test.com/$1 permanent;
}
}
permanent为永久重定向,状态码为301,如果写redirect则为302
12.10 Nginx访问日志
vim test.com.conf
access_log /tmp/test.log combined_realip;
12.11 Nginx日志切割
cd /usr/local/sbin
日志切割脚本
#! /bin/bash
## 假设nginx的日志存放路径为/data/logs/
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`
12.12 静态文件不记录日志和过期时间
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 7d;
access_log off;
}
location ~ .*\.(js|css)$
{
expires 12h;
access_log off;
}
访问js的静态文件就不记录日志
12.13 Nginx防盗链
~* 忽略大小写
vim 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 ;
if ($invalid_referer) {
return 403;
}
access_log off;
}
-e 指定referer 返回403 Forbidden
12.14 Nginx访问控制
针对目录的访问控制
允许的IP返回的是200,拒绝的IP返回的是403
匹配正则(之前举过的例子,一句话木马,解析php)
location ~ .*(upload|image)/.*\.php$
{
deny all;
}
1.php 拒绝访问
1.txt 可以访问
查看访问日志
之前举过的例子,防止CC攻击
if ($http_user_agent ~ 'Spider/3.0|YoudaoBot|Tomato')
{
return 403;
}
~* 波浪号后面加个星号,表示不区分大小写
if ($http_user_agent ~* 'Spider/3.0|YoudaoBot|Tomato')
{
return 403;
}
12.15 Nginx解析php相关配置
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;
}
fastcgi_pass unix:/tmp/php-fcgi.sock;
12.16 Nginx代理
server
{
listen 80;
server_name ask.apelearn.com;
location /
{
proxy_pass http://121.201.9.155/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
课堂串讲链接