Nginx配置try_files实践一

时间:2023-03-10 05:31:30
Nginx配置try_files实践一

参考资料:

http://linuxplayer.org/2013/06/nginx-try-files-on-multiple-named-location-or-server
http://*.com/questions/20426812/nginx-try-files-alias-directives

1. 环境:

OS:Ubuntu 15.10

nginx:nginx/1.9.3 (Ubuntu)

假设有两台虚拟机db1(IP:10.0.1.62)/db2(IP:10.0.1.63),通过try_files配置,使两台机器的/data/www/upload合集组成网络资源,设计思路如下:

Nginx配置try_files实践一

若请求到db1:

  • 检索db1是否存在目标资源,若存在则返回,否则请求通过db2-proxy重定向到db2
  • 检索db2是否存在目标资源,若存在则返回,否则返回404
  • 请求结束

若请求到db2同理。

2. 配置两台机器的nginx.conf

...

http {

    log_format  main  '[$content_type]--[$remote_addr] - $remote_user [$time_local] "[$request]" '
'[$status] $body_bytes_sent [$request_body] "$http_referer" '
'"$http_user_agent" $http_x_forwarded_for'; ... include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}

3. 为db1添加/etc/nginx/conf.d/db1.conf

 server{
listen ;
server_name 10.0.1.62;
error_page /.html; access_log /var/log/nginx/db1_access.log main;
error_log /var/log/nginx/db1_error.log; location /upload
{
root /data/www;
try_files $uri @db2;
} location /proxy/upload
{
alias /data/www/upload;
} location @db2{
proxy_pass http://10.0.1.63/proxy$uri;
}
}

4. 为db2添加/etc/nginx/conf.d/db2.conf

 server{
listen ;
server_name 10.0.1.63;
error_page /.html; access_log /var/log/nginx/db2_access.log main;
error_log /var/log/nginx/db2_error.log; location /upload
{
root /data/www;
try_files $uri @db1;
} location /proxy/upload
{
alias /data/www/upload;
} location @db1{
proxy_pass http://10.0.1.62/proxy$uri;
}
}

5. 重新加载nginx配置

`service nginx reload`

6. 在db1创建测试文件

Nginx配置try_files实践一

7. 在db2创建测试文件

Nginx配置try_files实践一

8. 访问结果

http://10.0.1.62/upload/db1.html Nginx配置try_files实践一
http://10.0.1.62/upload/db2.html  Nginx配置try_files实践一
http://10.0.1.63/upload/db1.html?a=1  Nginx配置try_files实践一
http://10.0.1.63/upload/db2.html?bfdsfads^*()^&  Nginx配置try_files实践一
http://10.0.1.63/upload/db3.html  Nginx配置try_files实践一
http://10.0.1.62/upload/db1/test.html  Nginx配置try_files实践一
http://10.0.1.62/upload/db2/test.html  Nginx配置try_files实践一
http://10.0.1.63/upload/db1/test.html  Nginx配置try_files实践一
http://10.0.1.63/upload/db2/test.html  Nginx配置try_files实践一
http://10.0.1.63/upload/db3/test.html  Nginx配置try_files实践一

9. 引申

由于生产环境的特殊原因,用户的请求可能是HTTP/HTTPS协议,那么本文的配置有很大的缺陷,解决方案见《Nginx配置try_files实践二