为nginx中的所有json文件启用内容类型application / json

时间:2014-07-29 17:21:34

标签: json nginx content-type

目前我在NGINX中面临启用内容类型的问题。  您可以在nginx.conf中看到默认内容类型为application/octet-stream

我在NGINX中配置了5个虚拟主机,我希望使用Content-Type application / json提供所有json文件。

我添加了“application / json json;”在mime.type文件中并重新启动了nginx服务,但是当我访问任何json文件时,它仍然是由content-type application / octet-stream来的。

我还需要做什么来将JSON文件作为application / json提供吗?

### curl -v http://www.ajay.com/abc/def/ghi/jkl/mno.json

* Hostname was NOT found in DNS cache
*   Trying xx.xx.xx.xx...
* Connected to www.ajay.com (xx.xx.xx.xx) port 80 (#0)
> GET abc/def/ghi/jkl/mno.json HTTP/1.1
> User-Agent: curl/7.36.0
> Host: www.ajay.com
> Accept: */*
< HTTP/1.1 200 OK
< Accept-Ranges: bytes
< Cache-Control: max-age=86400
< **Content-Type: application/octet-stream**
< Date: Tue, 29 Jul 2014 17:03:53 GMT
< ETag: "ab9b7b2c58d3a481e172aea95b1e87a0"
< Expires: Wed, 30 Jul 2014 17:03:53 GMT
< Last-Modified: Fri, 25 Jul 2014 13:18:14 GMT
* Server nginx is not blacklisted
< Server: nginx
< Content-Length: 603
< Connection: keep-alive
.
.
.

[root@ajay nginx]# nginx -v
nginx version: nginx/1.4.3
[root@ajay nginx]# ls -lh mime.types
-rw-r--r-- 1 root root 3.5K Jul 29 10:36 mime.types

我的mime.types文件

[root@ajay nginx]# cat mime.types

types {
text/html                             html htm shtml;
text/css                              css;
text/xml                              xml;
image/gif                             gif;
image/jpeg                            jpeg jpg;
**application/json                      json;**
application/x-javascript              js;
application/atom+xml                  atom;
application/rss+xml                   rss;

text/mathml                           mml;
text/plain                            txt;
text/vnd.sun.j2me.app-descriptor      jad;
text/vnd.wap.wml                      wml;
text/x-component                      htc;

image/png                             png;
image/tiff                            tif tiff;
image/vnd.wap.wbmp                    wbmp;
image/x-icon                          ico;
image/x-jng                           jng;
image/x-ms-bmp                        bmp;
image/svg+xml                         svg svgz;
image/webp                            webp;

application/java-archive              jar war ear;
application/mac-binhex40              hqx;
application/msword                    doc;
application/pdf                       pdf;
application/postscript                ps eps ai;
application/rtf                       rtf;
application/vnd.ms-excel              xls;
application/vnd.ms-powerpoint         ppt;
application/vnd.wap.wmlc              wmlc;
application/vnd.google-earth.kml+xml  kml;
application/vnd.google-earth.kmz      kmz;
application/x-7z-compressed           7z;
application/x-cocoa                   cco;
application/x-java-archive-diff       jardiff;
application/x-java-jnlp-file          jnlp;
application/x-makeself                run;
application/x-perl                    pl pm;
application/x-pilot                   prc pdb;
application/x-rar-compressed          rar;
application/x-redhat-package-manager  rpm;
application/x-sea                     sea;
application/x-shockwave-flash         swf;
application/x-stuffit                 sit;
application/x-tcl                     tcl tk;
application/x-x509-ca-cert            der pem crt;
application/x-xpinstall               xpi;
application/xhtml+xml                 xhtml;
application/zip                       zip;

application/octet-stream              bin exe dll;
application/octet-stream              deb;
application/octet-stream              dmg;
application/octet-stream              eot;
application/octet-stream              iso img;
application/octet-stream              msi msp msm;

audio/midi                            mid midi kar;
audio/mpeg                            mp3;
audio/ogg                             ogg;
audio/x-m4a                           m4a;
audio/x-realaudio                     ra;

video/3gpp                            3gpp 3gp;
video/mp4                             mp4;
video/mpeg                            mpeg mpg;
video/quicktime                       mov;
video/webm                            webm;
video/x-flv                           flv;
video/x-m4v                           m4v;
video/x-mng                           mng;
video/x-ms-asf                        asx asf;
video/x-ms-wmv                        wmv;
 video/x-msvideo                       avi;
}

我的nginx.conf文件

user              nginx;
worker_processes  1;
error_log         /var/log/nginx/error.log  notice;
pid               /var/run/nginx.pid;
worker_rlimit_nofile 30000;
events {
    worker_connections  1024;
}
http {
    include       /etc/nginx/mime.types;
default_type  application/octet-stream;
log_format combined_time '$remote_addr - $remote_user [$time_local]'
                '"$request" $status $body_bytes_sent '
                '"$http_referer" "$http_user_agent" $request_time';
access_log  /var/log/nginx/access.log  combined_time;
## Size Limits
client_body_buffer_size      16k;
client_header_buffer_size     1k;
client_max_body_size         20k;
large_client_header_buffers 4 4k;
## Timeouts
client_body_timeout     5;
client_header_timeout   5;
keepalive_timeout     5 5;
send_timeout            5;
## General Options
ignore_invalid_headers   on;
keepalive_requests        2;
recursive_error_pages    on;
server_tokens           off;
server_name_in_redirect off;
sendfile                 on;
## TCP options
tcp_nopush  on;
tcp_nodelay on;
## Compression
gzip                 on;
gzip_static          on;
gzip_buffers      16 8k;
gzip_http_version   1.0;
gzip_comp_level       6;
gzip_min_length     100;
gzip_types          text/plain application/xml application/x-javascript  text/xml text/css image/x-icon image/gif image/jpeg;
gzip_vary            on;
gzip_disable        "MSIE [1-6]\.";
include /etc/nginx/conf.d/*.conf;
}

请帮我解决这个问题

2 个答案:

答案 0 :(得分:2)

好的,我解决了这个问题。

  • 应修改./conf/mime.types.default添加
    application/json json;

  • ./sbin/nginx -s reload

答案 1 :(得分:0)

如果你的 json 文件没有扩展名,在测试短语中你可以将 const SCOPES = ['https://www.googleapis.com/auth/drive.readonly']; const Project: React.FC<ProjectInput> = () => { const [googleToken, setGoogleToken] = useState<string>(); const [googleData, setGoogleData] = useState<any>({}); const [documentData, setDocumentData] = useState(); const downloadGoogleDoc = async (authToken: string, fileID: string) => { try { const res = await axios.get(`https://www.googleapis.com/drive/v3/files/${fileID}/export`, { headers: { 'Authorization': `Bearer ${authToken}` } }); console.log(res); } catch(e) { console.log(e); console.log(e.message); } }; console.log(googleToken); console.log(googleData); const MyCustomButton = () => { return ( <button className="mx-8 my-2 p-2 rounded bg-blue-500 text-white"> Select From Google Drive </button> ) } if (googleToken && googleData.docs) { downloadGoogleDoc(googleToken, googleData.docs[0].id); } return ( <div className={`ml-${sideBarWidth}`}> <FadeIn> <div className="flex flex-col min-h-screen bg-gray-500 py-6 justify-center sm:py-12"> <div className="py-3 sm:max-w-xl sm:mx-auto"> <div className="bg-white min-w-1xl flex flex-col rounded-xl shadow-lg"> <div className="flex"> <div> <div> <div className="px-8 py-5"> <h2 className="text-gray-800 text-3xl font-semibold">Great! Select the document you'd like us to scan</h2> </div> </div> <GooglePicker clientId={process.env.REACT_APP_GOOGLE_CLIENT_ID} developerKey={process.env.REACT_APP_GOOGLE_API_KEY} scope={SCOPES} onAuthenticate={(token: any) => { setGoogleToken(token) }} onChange={(data: any) => { setGoogleData(data); nextOnboardingStage(); }} onAuthFailed={(data: any) => console.log('on auth failed:', data)} multiselect={true} navHidden={true} authImmediate={false} mimeTypes={['application/vnd.google-apps.document']} viewId={'DOCS'}> <MyCustomButton /> </GooglePicker> </div> </div> </div> </div> </div> </FadeIn> </div> ); }; export default Project; 修改成这样:

  const downloadGoogleDoc = async (authToken: string, fileID: string) => {
    try {
      const params = new URLSearchParams([['mimeType', 'text/html']]);
      const res = await axios.get(`https://www.googleapis.com/drive/v3/files/${fileID}/export`, {
        params,
        headers: {
          'Authorization': `Bearer ${authToken}`
        }
      });
      console.log(res);
    } catch(e) {
      console.log(e);
      console.log(e.message);
    }
  };

然后没有扩展名的文件以 nginx.conf 提供。