Nginx 基础

Updated on with 0 views and 0 comments

Nginx

一、 基础命令

nginx

nginx              # 启动
nginx -s stop      # 快速停止
nginx -s quit      # 优雅停止
nginx -s reload    # 热重载配置(不中断业务)
nginx -s reopen    # 重新打开日志文件
nginx -t           # 检查配置语法
nginx -V           # 查看编译参数、模块

systemctl

systemctl status nginx       # 查看 Nginx 状态
systemctl start nginx        # 启动
systemctl stop nginx 	     # 停止
systemctl restart nginx      # 重启(先停再起)
systemctl reload nginx       # 重载配置(不中断业务,优先用这个)
systemctl enable nginx       # 设置开机自启
systemctl enable nginx --now # 设置开机自启并且立即启动
systemctl disable nginx      # 关闭开机自启
nginx -t           	     # 检查配置语法

二、核心配置结构

# 全局块
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# events 块
events {
    worker_connections 1024;  # 单个worker连接数
}

# http 块
http {
    include       mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" "$http_user_agent"';

    access_log  /var/log/nginx/access.log  main;

    sendfile on;
    keepalive_timeout 65;

    # server 块(一个站点)
    server {
        listen 80;
        server_name www.xxx.com;

        # location 块
        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
        }

        # 反向代理
        location /api/ {
            proxy_pass http://127.0.0.1:8080;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }
}

三、最常用功能

1. 反向代理****

location / {
    proxy_pass http://127.0.0.1:8080;
}

2. 负载均衡

upstream backend {
    server 10.0.0.1:8080;
    server 10.0.0.2:8080;
}
server {
    location / {
        proxy_pass http://backend;
    }
}

3. 伪静态 / 地址重写

location / {
    rewrite ^/article/(\d+)$ /info.php?id=$1 last;
}

4. 访问控制

allow 192.168.1.0/24;
deny all;

5. 图片 / 静态文件缓存

location ~* \.(jpg|jpeg|png|css|js)$ {
    expires 7d;
}

6. 证书配置

ssl_certificate:公钥证书(.crt/.pem

ssl_certificate_key:私钥(.key

路径自己改,权限建议 600。 chmod 600 path

server {
    listen 80;
    server_name yourdomain.com;
    # HTTP 强制跳转 HTTPS
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name yourdomain.com;

    # 证书路径(crt/cer/pem 都可以)
    ssl_certificate /etc/nginx/ssl/yourdomain.crt;
    ssl_certificate_key /etc/nginx/ssl/yourdomain.key;

    # 基础 SSL 安全配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;
}

四、日志查看

image.png

五、状态码排查

  • 200:正常
  • 301/302:重定向
  • 403:权限不足、禁止访问、目录无索引页
  • 404:文件不存在、路径错、location 匹配不到
  • 499:客户端主动断开(常见于请求超时)
  • 502:后端服务没启动 / 端口不通 / 拒绝连接
  • 504:后端服务执行太慢,超时了

六、Nginx 起不来常见原因

  • 80 端口被占用
ss -tulnp | grep :80
  • 配置文件语法错
nginx -t
  • 权限不足
  • 磁盘满 /inode 满
  • SELinux 拦截
  • 防火墙拦截443/80端口

标题:Nginx 基础
作者:zhongts
地址:http://zhongts.cc:8080/articles/2026/04/04/1775287440372.html