22 Nginx配置文件nginx.conf的文件结构

22 Nginx配置文件nginx.conf的文件结构

Nginx 核心配置文件默认放在 /usr/local/nginx/conf/nginx.conf ,接下来学习 nginx.conf 内容和基本配置方法

22.1 nginx.conf

Nginx 自带的Nginx 配置文件,将其中注释部分删除后内容:(Nginx配置文件使用# 注释)

[root@nginx-100 ~]# cat /usr/local/nginx/conf/nginx.conf
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

配置文件默认分为三大块:全局块、events 块、http 块

全局块:在 events 块、http 块等外部编写的内容,用于设置Nginx服务器整体运行的配置指令名、指令值

events 块:nginx 服务器用来配置与用户网络连接的相关内容

http 块:nginx服务器配置中最重要,涉及:nginx 代理、缓存、日志记录、第三方模块等功能的配置,http 块中也有自己使用的指令名、指令值

  server 块:一个 http 块中可以配置多个 server 块,配置与虚拟主机相关内容 listen、server_name

  location 块:一个 server 块中可以配置多个 location 块,匹配 location 后面的路径,从 location 指定的资源中取对应的内容,交还给客户端

 error_page: 错误码为固定的值时,跳转到的目录和文件

 

22.2 演示

浏览器访问:http://10.0.0.100/ 正常返回

image

浏览器访问:http://10.0.0.100/welcome.html 返回 404,没有此文件或目录

image

修改返回 404 状态码为错误页面

[root@nginx-100 ~]# cat /usr/local/nginx/conf/nginx.conf
..........
        error_page   500 502 503 504 404 /50x.html;
        location = /50x.html {
            root   html;
..........
[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/welcome.html 返回配置的错误页面

image

验证访问的是错误页面内容,修改错误页面

[root@nginx-100 ~]# cat /usr/local/nginx/html/50x.html
<!DOCTYPE html>
<html>
<head>
<title>Error</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>An error occurred.</h1>
<p>Sorry, the page you are looking for is currently unavailable.<br/>
Please try again later.</p>
<p>If you are the system administrator of this resource then you should check
the error log for details.</p>
<p><em>Faithfully yours, nginx.</em></p>
<p><em>This is a error Page.</em></p>
</body>
</html>

浏览器访问:http://10.0.0.100/welcome.html 返回配置的错误页面(新增了内容)

image

[root@nginx-100 ~]# cat /usr/local/nginx/html/welcome.html
<h1>Welcome to nginx !!!</h1>

浏览器访问:http://10.0.0.100/welcome.html 返回正常内容

image

22.3 小结

nginx.conf 配置文件中默认分为三大块:全局块、events 块、http 块

一个 http 块中可以配置多个 server 块,一个 server 块中可以配置多个 location 块

———————————————————————————————————————————————————————————————————————————

                                                                                                                         无敌小马爱学习

posted on 2026-03-23 14:55  马俊南  阅读(1)  评论(0)    收藏  举报