參考資料:html
http://linuxplayer.org/2013/06/nginx-try-files-on-multiple-named-location-or-server
http://stackoverflow.com/questions/20426812/nginx-try-files-alias-directiveslinux
1. 環境:nginx
OS:Ubuntu 15.10網絡
nginx:nginx/1.9.3 (Ubuntu)post
假設有兩臺虛擬機db1(IP:10.0.1.62)/db2(IP:10.0.1.63),經過try_files配置,使兩臺機器的/data/www/upload合集組成網絡資源,設計思路以下:測試
若請求到db1:url
若請求到db2同理。spa
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.conf3d
server{ listen 80; server_name 10.0.1.62; error_page 404 /404.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 80; server_name 10.0.1.63; error_page 404 /404.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建立測試文件
7. 在db2建立測試文件
8. 訪問結果
http://10.0.1.62/upload/db1.html |
|
http://10.0.1.62/upload/db2.html |
|
http://10.0.1.63/upload/db1.html?a=1 |
|
http://10.0.1.63/upload/db2.html?bfdsfads^*()^& |
|
http://10.0.1.63/upload/db3.html |
|
http://10.0.1.62/upload/db1/test.html |
|
http://10.0.1.62/upload/db2/test.html |
|
http://10.0.1.63/upload/db1/test.html |
|
http://10.0.1.63/upload/db2/test.html |
|
http://10.0.1.63/upload/db3/test.html |
|
9. 引伸
因爲生產環境的特殊緣由,用戶的請求多是HTTP/HTTPS協議,那麼本文的配置有很大的缺陷,解決方案見《Nginx配置try_files實踐二》