Nginx 配置解析

参考

Nginx 配置文件示例

  • 简单的HTTP配置
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    # /etc/nginx/conf.d/default.conf 一般nginx配置在这个位置
    server {
    # 监听80端口
    listen 80;

    location / {
    # 指定静态页面的根目录
    root /usr/share/nginx/html;

    # 指定默认首页
    index index.html;

    # 按照指定的顺序检查文件是否存在,并根据结果处理请求。
    # $uri:首先尝试将请求的URI直接映射到文件系统上的一个文件。例如,如果请求的是 /img/photo.png,Nginx会检查 /usr/share/nginx/html/img/photo.png 是否存在。
    # $uri/:如果上述步骤失败(即找不到对应的文件),则尝试将其视为一个目录,并查找该目录下的默认索引文件(如由 index 指令指定的 index.html)。
    try_files $uri $uri/ @rewrites;
    }

    location @rewrites {
    rewrite ^(.+)$ /index.html last;
    }
    }

  • HTTPS配置
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    server {
    listen 80;
    server_name exwckv.top;
    return 301 https://exwckv.top; # 将所有HTTP请求重定向到HTTPS
    }

    server {

    # 添加 ssl 参数表示通过此端口进行的所有通信都应使用SSL/TLS加密。需配置SSL证书和私钥文件的位置
    listen 443 ssl;

    # 如果没有域名,可以省略 server_name 指令
    # 或者直接指定服务器的公网IP地址
    server_name exwckv.top;

    ssl_certificate /etc/nginx/certs/fullchain.pem; # 指定SSL证书的位置
    ssl_certificate_key /etc/nginx/certs/privkey.pem; # 指定SSL私钥的位置

    location / {
    root /usr/share/nginx/html;
    index index.html;
    try_files $uri $uri/ @rewrites;
    }

    location @rewrites {
    rewrite ^(.+)$ /index.html last;
    }
    }

常用nginx指令

  • nginx -t: 检查配置文件是否有误
  • nginx -s reload: 重载配置文件,不会重启服务器,只是重新加载配置文件,不会影响正在运行的服务