当访问静态页面的时候location匹配到 (html|jpg|png|js|css|gif|bmp|jpeg) 通过转发到静态服务器,静态服务通过location的正则匹配来处理请求。
当访问动态页面时location匹配到(php|jsp)结尾的文件转发到后端php服务处理请求。
配置nginx反向代理upstream
upstream static {
server 10.0.105.196:80;
}
upstream php {
server 10.0.105.200:80;
}
server {
listen 80;
server_name localhost;
#动态资源加载
location ~ \.(php|jsp)$ {
proxy_pass http://php;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
#静态资源加载
location ~ .*\.(html|gif|jpg|png|bmp|swf|css|js)$ {
proxy_pass http://static;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
两个网站A和B,A网站引用了B网站上的图片,这种行为就叫做盗链。防盗链,就是要防止A引用B的图片。
ngx_http_referer_module
vim /etc/nginx/nginx.conf
# 日志格式添加"$http_referer"
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
Syntax: valid_referers none | blocked | server_names | string ...;
Default: —
Context: server, location
none : 允许没有http_refer的请求访问资源;
blocked : 允许不是http://开头的,不带协议的请求访问资源;
server_names : 只允许指定ip/域名来的请求访问资源(白名单);
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
valid_referers none blocked 主机或者域名; //设置白名单
if ($invalid_referer) {
return 502; //返回状态码
}
}
}