Why request without suffix of filename extension h

2019-08-13 23:09发布

问题:

I want to test the nginx‘s echo module.And I want to echo the url of what I type in browser.

My nginx configuration:

   index  index.php index.html index.htm index.nginx-debian.html ;

   location / {               
       try_files $uri $uri/  /index.php  =404;              
   }
   location  /hello {
   echo $request_uri;
   }

input url : http://127.0.0.1/hello/.

return : return a file and the file have content : /hello/


input url: http://127.0.0.1/hello/hi

return : return a file and the file have content : /hello/hi


input url:http://127.0.0.1/hello/hi.html

return: print /hello/hi.html in browser.


My question: Why the url without the html suffix will become download file? How to fix it ? I just want to print the url in browser.

回答1:

nginx determines the Content-Type from the extension. These are included from a file called mime-types. You can override this behaviour by placing a default-type directive in the location block. For example:

location  /hello {
    types {}
    default_type    text/html;
    echo $request_uri;
}

See this doucument for more.



回答2:

Whether browser would render the page/download file finally depends on other factors, for example, 'Content-type' /'Content-Disposition' in http header

Content-Disposition takes one of two values, `inline' and
`attachment'.  `Inline' indicates that the entity should be
immediately displayed to the user, whereas `attachment' means that
the user should take additional action to view the entity.

You may check and compare the http responses when visiting /hello/hi or /hello/hi.html, to examine that at least one of these two headers may not be correctly set, in this case it is more possibly content-type is not 'text/html' here

A solution would be specifying content-type for your path, may be like

location  /hello {
  default_type "text/html";
  echo $request_uri;
}

or

location  /hello {
  add_header  Content-Type 'text/javascript;charset=utf-8';
  echo $request_uri;
}