13 10 月 2026

Nginx 是目前最主流的 Web 服务器,占据全球超过三成的网站。它轻量、稳定、并发能力强,也是反向代理和负载均衡的首选。

这篇从安装开始,带你配出第一个可访问的站点,并讲清配置文件的结构和常用指令。

需要一台服务器练手?财富云计算 提供云服务器;搭建内网服务、测试环境、游戏服务端可选 NAT 型(无独立公网 IP,价格比独立 IP 机型省一半以上)。

一、安装 Nginx

Debian / Ubuntu

apt update
apt install nginx -y
nginx -v
systemctl enable --now nginx

CentOS / Rocky / AlmaLinux

yum install epel-release -y
yum install nginx -y
systemctl enable --now nginx

验证

systemctl status nginx
curl -I http://127.0.0.1

浏览器访问 http://服务器IP,看到 "Welcome to nginx" 就成功了。

如果打不开,检查防火墙和安全组:

# Ubuntu
ufw allow 'Nginx Full'      # 放行 80 和 443
ufw status

# CentOS
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

# 别忘了云平台控制台的安全组也要放行 80/443

二、目录结构

/etc/nginx/
├── nginx.conf                  # 主配置文件
├── conf.d/*.conf               # 额外配置(会被主配置 include)
├── sites-available/            # 可用站点(Debian/Ubuntu 特有)
├── sites-enabled/              # 已启用站点(是 sites-available 的软链接)
├── modules-enabled/
└── mime.types

/var/www/html/                  # 默认网站根目录
/var/log/nginx/
├── access.log                  # 访问日志
└── error.log                   # 错误日志

Debian/Ubuntu 推荐做法:每个站点在 /etc/nginx/sites-available/ 建一个配置文件,然后软链接到 sites-enabled/:

ln -s /etc/nginx/sites-available/mysite /etc/nginx/sites-enabled/

CentOS 推荐做法:直接在 /etc/nginx/conf.d/ 下建 xxx.conf。


三、第一个站点配置

mkdir -p /var/www/mysite
echo "<h1>Hello Nginx</h1>" > /var/www/mysite/index.html
nano /etc/nginx/sites-available/mysite

最小可用配置:

server {
    listen 80;
    server_name example.com www.example.com;

    root /var/www/mysite;
    index index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }
}

启用并测试:

ln -s /etc/nginx/sites-available/mysite /etc/nginx/sites-enabled/
nginx -t              # ⚠️ 每次改配置都要先测试
systemctl reload nginx

nginx -t 是最重要的习惯——它会检查语法,报错就别 reload,否则可能把网站搞挂。


四、核心指令详解

server 块

一个 server 就是一个虚拟主机(站点)。可以写多个。

server {
    listen 80;                    # 监听端口
    listen [::]:80;               # IPv6
    listen 443 ssl http2;         # HTTPS + HTTP/2
    server_name a.com *.a.com;    # 域名,支持通配符
    server_name _;                # 默认(兜底)站点
    root /var/www/a;
    index index.php index.html;
    charset utf-8;
    client_max_body_size 20m;     # 上传大小限制(默认 1m,常被吐槽)
}

location 块:匹配 URL

location / { }                    # 前缀匹配,匹配所有
location = /login { }             # 精确匹配(优先级最高)
location /api/ { }                # 前缀匹配
location ~ \.php$ { }             # 正则匹配(区分大小写)
location ~* \.(jpg|png|gif)$ { }  # 正则匹配(忽略大小写)
location ^~ /static/ { }          # 前缀匹配,且不再检查正则

优先级:= > ^~ > 正则(按配置顺序) > 普通前缀

常用 location 示例

# 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2)$ {
    expires 30d;
    add_header Cache-Control "public, immutable";
    access_log off;
}

# 禁止访问隐藏文件(如 .git、.env)
location ~ /\. {
    deny all;
    access_log off;
    log_not_found off;
}

# 禁止访问特定后缀(防止备份文件泄露源码)
location ~* \.(sql|bak|swp|old|zip|tar\.gz)$ {
    deny all;
}

# PHP 转发
location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php8.2-fpm.sock;
}

五、日志配置

http {
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for" '
                    'rt=$request_time urt=$upstream_response_time';

    access_log /var/log/nginx/access.log main;
    error_log /var/log/nginx/error.log warn;
}

加上 $request_time 和 $upstream_response_time 后,排查慢请求会非常方便。

日志切割:Nginx 的日志不会自动轮转,用 logrotate:

cat /etc/logrotate.d/nginx
/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
    endscript
}

手动测试:logrotate -d /etc/logrotate.d/nginx


六、性能相关配置

在 /etc/nginx/nginx.conf 的 http 块里:

worker_processes auto;              # 通常等于 CPU 核数
worker_connections 1024;            # 每个 worker 的最大连接数

sendfile on;                        # 零拷贝传输,静态文件更快
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
server_tokens off;                  # 隐藏版本号(安全)

# Gzip 压缩
gzip on;
gzip_vary on;
gzip_comp_level 6;
gzip_min_length 1024;
gzip_proxied any;
gzip_types text/plain text/css text/xml application/json
           application/javascript application/xml application/xml+rss
           image/svg+xml;

# 文件描述符缓存
open_file_cache max=10000 inactive=30s;
open_file_cache_valid 60s;
open_file_cache_min_uses 2;

最大并发数 = worker_processes × worker_connections(粗略)。

系统层面也要调:

ulimit -n                 # 查看句柄上限
# 修改 /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535

七、HTTPS 配置

server {
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;

    root /var/www/mysite;
    index index.html;
}

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

证书申请详见本站《免费 SSL 证书申请与 HTTPS 部署》。


八、常用场景配置片段

反代到本地服务(如 Node/Java 应用)

location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

单页应用(React/Vue history 路由)

location / {
    try_files $uri $uri/ /index.html;
}

防盗链

location ~* \.(jpg|png|gif|mp4)$ {
    valid_referers none blocked server_names *.example.com;
    if ($invalid_referer) {
        return 403;
    }
}

限速(防下载跑满带宽)

location /download/ {
    limit_rate 500k;        # 每连接限速
}

拒绝指定 UA / IP

if ($http_user_agent ~* (curl|wget|scrapy)) {
    return 403;
}
deny 1.2.3.4;
allow 192.168.0.0/16;
deny all;

九、常见错误与排查

现象排查
502 Bad Gateway后端服务没起来 / fastcgi_pass 路径错 → 看 error.log
504 Gateway Timeout后端处理超时 → 加大 proxy_read_timeout
403 Forbidden目录无 x 权限、文件无 r 权限、index 文件不存在、SELinux
404 Not Foundroot 路径错、try_files 配置问题
413 Request Entity Too Largeclient_max_body_size 太小
nginx: [emerg] bind() to 0.0.0.0:80 failed端口被占用 → `ss -tulnp \grep :80`
改了配置不生效没 reload / 没 -t 就 reload 失败了
中文文件名乱码加 charset utf-8;

查错误日志是第一步:

tail -50 /var/log/nginx/error.log
tail -f /var/log/nginx/error.log

十、安全加固要点

server_tokens off;                  # 隐藏版本

# 安全响应头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;

# 禁止访问敏感文件
location ~ /\. { deny all; }
location ~* \.(sql|bak|swp|old)$ { deny all; }

# 限制请求方法
if ($request_method !~ ^(GET|HEAD|POST)$) {
    return 405;
}

更多防护见本站《网站常见漏洞与基础防护》。


十一、Nginx 日常命令

nginx -t                      # 语法测试(必做)
nginx -T                      # 测试并输出完整配置
systemctl start nginx
systemctl stop nginx
systemctl restart nginx       # 重启(会短暂中断)
systemctl reload nginx        # 平滑重载(推荐,不断连接)
systemctl status nginx
journalctl -u nginx -f        # 实时日志
nginx -s reload               # 另一种重载方式
nginx -V                      # 查看编译参数与模块

十二、下一步

搭好 Nginx 之后,通常按这个顺序继续:

  1. 配 HTTPS → 《免费 SSL 证书申请与 HTTPS 部署》
  2. 域名解析 → 《域名解析与 DNS 记录详解》
  3. 多站点/反代 → 《Nginx 反向代理与多站点配置》
  4. 装 PHP + 数据库 → 《用云服务器搭建 Typecho 博客》
  5. 性能优化 → 《网站打开慢的排查流程》

建站推荐从一台稳定的云服务器开始。财富云计算 提供独立 IP 云服务器(适合对外网站)和 NAT 型云服务器(无独立公网 IP,价格比独立 IP 机型省一半以上,适合内网服务、测试环境、游戏服务端)。建议先摸清需求再选配置,避免一开始买大了浪费。

相关阅读:

  • 《免费 SSL 证书申请与 HTTPS 部署》
  • 《Nginx 反向代理与多站点配置》
  • 《域名解析与 DNS 记录详解》
延伸阅读
  1. 网站环境怎么选:LNMP 手动 / 宝塔面板 / Docker / 云开发
  2. 问卷表单系统搭建:SurveyKing / Formbricks,数据自己收
  3. 图床搭建:Lsky Pro / Lychee,自托管图片托管方案
  4. 邮件列表搭建:listmonk 自托管 Newsletter,把读者握在自己手里
  5. 文档站点搭建:MkDocs / VuePress / Docsify,产品文档与技术手册方案
  6. RSS 阅读器搭建:FreshRSS 自托管,把信息流拿回自己手里
  7. 短链接服务搭建:Shlink 自托管,链接数据自己掌握
  8. 网站状态监控页搭建:Uptime Kuma,服务器挂了第一时间知道
更多阅读
  1. 上一篇:服务器备份与快照策略:数据没了才想起备份就晚了
  2. 下一篇:免费 SSL 证书申请与 HTTPS 部署:Let's Encrypt 完整流程
发表评论 5