5.3 Nginx 動靜分離
Server 腳本片段
server { listen 80; server_name ccserver1; #charset koi8-r; access_log logs/host.access.log main; index index.html index.htm index.jsp; root /usr/tomcat-8.0.0-RC5-1/webapps/ROOT/; location ~* .*\.(jpg|jpeg|gif|png|swf|ico)$ {if (-f $request_filename){ break; } } location ~* .*\.(html|htm|js|css)$ { # express id; } location / { proxy_pass http://cctest1.com; # root html; # index index.html index.htm; }
備註:腳本片段,第一個,第二個lcation 是沒有配置proxy_pass 代理地址的,這個時候回默認到 root的下面去找靜態資源
root /usr/tomcat-8.0.0-RC5-1/webapps/ROOT/;
場景測試一
註釋:第一個,第二個location,查看tomcat的日誌信息
場景測試二
取消註釋:第一個,第二個location,查看tomcat的日誌信息
結果
實現了動靜分離
搭建我們自己電商平臺的動靜分離
訪問:http://172.20.10.5/architecture1web
結果(發現靜態資源圖片無法找到)
因此需要修改 nginx.conf配置文件裏面的root 路徑
修改前
root /usr/tomcat-8.0.0-RC5-1/webapps/ROOT/;
修改後
root /usr/tomcat-8.0.0-RC5-1/webapps
仍然找不到
檢查圖片地址(http://172.20.10.5/architecture1web/static/images/logo.jpg),但是172.20.10.5是nginx代理tomcat的地址,無法找到靜態資源
進入linux操作系統目錄查找是否有這個地址,發現沒有靜態資源
為什麽tomcat直接訪問路徑“http://172.20.10.5:8080/architecture1web/static/images/logo.jpg”的時候,可以直接訪問? spring mvc進行了一次路徑的映射轉換,因此才可以正常訪問
現在nginx直接進行靜態資源的訪問
拷貝wen-inf下面的static的目錄到architecture1web目錄
[root@eshop-cache04 WEB-INF]# cp -r static/ /usr/tomcat-8.0.0-RC5-1/webapps/architecture1web
檢查靜態資源
刷新頁面
實現動靜分離
電商平臺可以實現動靜分離,但是在訪問tomcat的時候,出現靜態資源訪問的異常(http://172.20.10.5/)
修改nginx.conf的配置文件
root /usr/tomcat-8.0.0-RC5-1/webapps/ROOT; location ~* ^/architecture1web/.*\.(jpg|jpeg|gif|png|swf|ico)${ root /usr/tomcat-8.0.0-RC5-1/webapps; } location ~* ^/architecture1web/.*\.(html|htm|js|css)${ root /usr/tomcat-8.0.0-RC5-1/webapps; }
[root@eshop-cache04 sbin]# ./nginx -s reload
檢查tomcat,一切正常
檢查電商平臺,一切正常
5.3 Nginx 動靜分離