28 Nginx的http块MIME-Type的使用
28 Nginx的http块MIME-Type的使用
28.1 定义MIME-Type
浏览器中可以显示的内容有HTML、XML、GIF 等种类繁多的文件、媒体等资源,浏览器为了区分这些资源,就需要使用MIME-Type,所以说 MIME-Type 是网络资源的媒体类型,Nginx 作为 web 服务器,也需要能够识别前端请求的资源类型
Nginx 的配置文件中,默认有两行配置:1.导入、2.前端响应类型
include mime.types;
default_type application/octet-stream;
28.2 default_type
default_type:用来配置Nginx响应前端请求默认的MIME类型
| 语法 | default_type mime-type; |
| 默认值 | default_type text/plain; |
| 位置 | http、server、location |
default_type 上面还有 include mime.types; ,include 前面介绍过,相当于把 mime.types 文件中 MIMT类型与相关类型文件的文件后缀名的对应关系加入到当前的配置文件中
当请求某些接口时,需要返回指定的文本字符串或 json字符串,如果逻辑非常简单或是固定的字符串,可以经nginx快速实现,无需编写程序,不仅减少服务器资源占用并且响应性能高
[root@nginx-100 ~]# cat /usr/local/nginx/conf/nginx.conf .......... location / { root /home/www; index index.html index.htm; } location /get_text { return 200 "<h1>This is Nginx's Text</h1>"; } ..........
# 重载配置文件 [root@nginx-100 ~]# /usr/local/nginx/sbin/nginx -t && /usr/local/nginx/sbin/nginx -s reload nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
浏览器访问:http://10.0.0.100/get_text

注意:octet-stream; 以二进制流的方式处理,会以下载附件的方式进行相应的操作
28.3 text/plain
[root@nginx-100 ~]# cat /usr/local/nginx/conf/nginx.conf .......... location /get_text { return 200 "<h1>This is Nginx's Text</h1>"; } location /get_text2 { default_type text/plain; return 200 "<h1>This is Nginx's Text</h1>"; } ..........
浏览器访问:http://10.0.0.100/get_text2

注意:text/plain; 是以文本展示
28.4 text/html
[root@nginx-100 ~]# cat /usr/local/nginx/conf/nginx.conf .......... location /get_text2 { default_type text/plain; return 200 "<h1>This is Nginx's Text</h1>"; } location /get_html { default_type text/html; return 200 "<h1>This is Nginx's Text</h1>"; } ..........
[root@nginx-100 ~]# /usr/local/nginx/sbin/nginx -t && /usr/local/nginx/sbin/nginx -s reload nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

注意:text/html; 是以前端页面展示
28.5 application/json
[root@nginx-100 ~]# cat /usr/local/nginx/conf/nginx.conf .......... location /get_html { default_type text/html; return 200 "<h1>This is Nginx's Text</h1>"; } location /get_json { default_type application/json; return 200 "{'username':'Tom','age':18}"; } ..........
[root@nginx-100 ~]# /usr/local/nginx/sbin/nginx -t && /usr/local/nginx/sbin/nginx -s reload nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
浏览器访问:http://10.0.0.100/get_json

注意:application/json; 是以json格式展示
———————————————————————————————————————————————————————————————————————————
无敌小马爱学习
浙公网安备 33010602011771号