1. 程式人生 > >5.3 Nginx 動靜分離

5.3 Nginx 動靜分離

找不到 直接 linux apps css 腳本 images 0.10 inf

技術分享圖片

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 動靜分離