十二周四次课(1月5日)
12.13 Nginx防盗链
[root@wwlinux701 ~]# vim /usr/local/nginx/conf/vhost/test.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;
}
#location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
# {
# expires 7d;
# access_log off;
# }
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;
}
access_log /tmp/test.conf.log combined_realip;
}
/usr/local/nginx/sbin/nginx -s reload
curl -e “http://www.baidu.com/1.txt” -x127.0.0.1:80 -I test.com/123.gif #自定义referer
curl -x127.0.0.1:80 -I test.com/123.gif
12.14 Nginx访问控制
[root@wwlinux701 ~]# vim /usr/local/nginx/conf/vhost/test.conf
server
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;
}
#location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
# {
# expires 7d;
# access_log off;
# }
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/
{
allow 192.168.133.1; #白名单
allow 127.0.0.1; #白名单
deny all;
}
access_log /tmp/test.conf.log combined_realip;
}
• 可以匹配正则
location ~ .(upload|image)/..php#匹配upload和image目录中php结尾的都不准解析
{
deny all;
}
•根据user_agent限制
if (http_user_agent ~ ‘Spider/3.0|YoudaoBot|Tomato’) #~*后面加个*就能忽略大小写
{
return 403;
}
• deny all和return 403效果一样
12.15 Nginx解析php相关配置
•配置如下: vim /usr/local/nginx/conf/vhost/test.conf
location ~ \.php$
{
include fastcgi_params;
fastcgi_pass unix:/tmp/php-fcgi.sock;
# fastcgi_pass 127.0.0.1:9000; 要看php-fpm中的配置是监听的哪个
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /data/wwwroot/test.com$fastcgi_script_name;
}
• fastcgi_pass 用来指定php-fpm监听的地址或者socket
如果是用的sock那么一定要放开php配置中的listen.mode=666(sock的权限位一定要有写的权限)
unix:/tmp/php-fcgi.sock这里的sock文件是php-fpm.conf中定义的
cat /usr/local/php-fpm/etc/php-fpm.conf配置文件中写什么就定义什么
如果php监听的是ip和端口,nginx中的配置文件就要改成
fastcgi_pass 127.0.0.1:9000;
fastcgi_param 中的路径也需要跟上面对应起来
/usr/local/nginx/sbin/nginx -s reload
12.16 Nginx代理
用户在没有直接访问web服务器的情况下。可以通过中间服务器代理访问web服务器
• cd /usr/local/nginx/conf/vhost
• vim proxy.conf //加入如下内容
server
{
listen 80;
server_name ask.apelearn.com;
location /
{
proxy_pass http://121.201.9.155/; #这个webip是论坛的ip
proxy_set_header Host $host; #$host就是server_name
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
配置好代理以后就能通过本地访问远程的server_name
curl ask.apelearn.com/robots.txt
curl -x127.0.0.1:80 ask.apelearn.com/robots.txt
扩展
502问题汇总
http://ask.apelearn.com/question/9109
location优先级
http://blog.lishiming.net/?p=100