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