ngixn 常用配置之文件类型与自定义 log

大家好,我是 17 。

总结了一些 nginx 的常用配置。从入口文件开始,今天讲一下文件类型和自定义log

为了讲述方便,环境为 CentOS 7, nginx 版本 1.21。

配置文件入口

/etc/nginx/nginx.conf

这是入口文件,这个文件里有这样一句:

include /etc/nginx/conf.d/*.conf;

各个网站的配置文件是放在 conf.d 目录下的。这里面的所有 .conf 文件都会被读取。我们增加一个 test.conf。 yourname 就是你的用户名。在 /home/yourname/web/test/ 下面增加一个 index.html文件 ,文件。文件内容为 hello。

server{
  listen 3000;
  server_name _;
  location / {
    root /home/yourname/web/test/;
  }
}

启动 nginx,如果已经启动,reload 配置文件。

# 启动
sudo nginx 
# 如果已经启动,重新加载配置
sudo nginx -s reload

用 ip 或 localhost:3000 用浏览器访问网站,显示 hello。测试方法也可以用 curl localhost:3000,这样可能会更方便些。

文件类型

对于我们请求的内容,浏览器的处理方式是不一样的。浏览器如何判断内容,是根据响应头 Content-Type
在入口配置文件 nginx.conf 中有这样两句:

include             /etc/nginx/mime.types;

default_type        application/octet-stream;

mine.types 是 Content-type 和文件后缀名的映射表。比如 xx.css 文件的 Content-typetext/css 。 default_type 是默认的 type。比如当访问 /a 的时候,如果 a 文件存在,nginx会返回 a 文件,响应头 Content-type:application/octet-stream。 浏览器对application/octet-stream的处理方式是下载,而不是展示。

如果我们的请求地址是这样的 /a.html,/b.css, nginx 都可以自动处理。但有的时候,可能请求的地址是这样的 /a,这时就需要我们手动指定 type 类型。指定 type 类型很简单,有两种方法。

location /css {
  add_header Content-type text/css;
}
location /css {
  default_type  text/css;
}

自定义log

打开 /etc/nginx/nginx.conf 找到 log_format

扫描二维码关注公众号,回复: 15431169 查看本文章
 log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

对于开发来说可以去掉 ua,ua 很长,去掉可以方便查看。尤其对于初学者,建议加上 $request_filename ,这个变量代表的是访问的实际文件路径,对于理解各种指令的效果,查找错误非常有帮助。

在入口的配置文件中用 Log_foramt定义了一个 main。我们可以定义一个 dev,按你所需求选用需要的内容即可。
使用的时候,直接用 dev这个名字就行。

 log_format  dev  '[$time_local] "$request" $request_filename'
                   '$status $body_bytes_sent "$http_referer" '
 access_log /home/duhongwei/log/access.log dev;

猜你喜欢

转载自blog.csdn.net/m0_55635384/article/details/129102397