nginx---訪問頁面不存在,顯示默認頁面


訪問網頁不存在顯示默認網頁

  一、修改配置

vim /etc/nginx/conf.d/test.conf 或者 vim /etc/nginx/nginx.conf 
server { server_name www.a.net; root /data/site1; location /about { root /opt/testdir/; index test.html; } location /test { root /opt/; try_files $uri /test/default.html =404; } error_page 404 =200  /404.html; location = /404.html { } } 

當訪問www.a.net下的test下的什么就顯示對應的/root/下的test目錄下的對應文件,當訪問不存在的頁面就顯示default.html,而默認的頁面default.html也找不到的話就顯示404頁面

  二、新建測試頁面

cd /opt/test
1 mkdir /opt/test/
2 echo "This is test1 page" > 1.html 3 echo "This is test2 page" > 2.html 4 echo "This is default page" > default.html

  三、測試訪問

1 [16:38:56 root@localhost ~]#curl www.a.net/test/1.html 2 This is test1 page 3 [16:39:42 root@localhost ~]#curl www.a.net/test/2.html 4 This is test2 page 5 [16:39:46 root@localhost ~]#curl www.a.net/test/2222.html 6 This is default page 7 [16:39:51 root@localhost ~]#curl www.a.net/test/244.html 8 This is default page

 刪除默認頁面繼續訪問,會顯示對應的404頁面內容

[16:39:58 root@localhost ~]#curl www.a.net/test/244.html
This is a error page

 圖片  

一、修改配置

server { server_name www.a.net; root /data/site1; location /about { root /opt/testdir/; index test.html; }  location /images { alias /data/images; try_files $uri /images/default.jpg;  } error_page 404 =200  /404.html; location = /404.html { } }

 

當訪問/images 時候,(try_files )嘗試去訪問對應的uri,這個uri是訪問的路徑什么就是什么,默認情況下如果能招到uri就顯示uri,找不着就顯示默認圖片

這里的/default.jpg對應的是/data/images

  二、新建測試文件

1 mkdir /data/images/
2 cp /usr/share/backgrounds/morning.jpg /data/images/a.jpg 3 cp /usr/share/backgrounds/night.jpg /data/images/b.jpg 4 cp /usr/share/backgrounds/day.jpg /data/images/default.jpg

  三、測試訪問

1、http://www.a.net/images/a.jpg

 

 2、http://www.a.net/images/b.jpg

3、訪問一個不存在的頁面

或者當訪問的內容不存在自動在后面補個后綴

server {
        server_name www.a.net;
        root /data/site1;
        location /about {
                root /opt/testdir/;
                index test.html;
        }
        location /test {
        root /opt/;
        try_files $uri $uri.jpg =404;
        }

        error_page 404 =200  /404.html;
        location = /404.html {
        }
}

 

 我這里使用的是系統里自帶的圖片做演示的,只有略微顏色區別。

京東就是這樣,訪問錯誤頁面會自動跳到首頁

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM