Nginx 基础配置教程

📅 2026-10-13 20:30 👤 ajie2012 📁 服务器运维 👁 1 阅读

Nginx 是最常用的 Web 服务器,跑网站、做反向代理都靠它。这篇讲最常用的配置。

一、安装

sudo apt update
sudo apt install nginx -y
sudo systemctl enable nginx
sudo systemctl start nginx

浏览器打开服务器 IP,能看到 Nginx 欢迎页说明装好了。

二、常用命令

sudo systemctl start nginx     # 启动
sudo systemctl stop nginx      # 停止
sudo systemctl restart nginx   # 重启
sudo systemctl reload nginx    # 重载配置(不断连)
sudo nginx -t                  # 测试配置文件语法

改完配置先 nginx -t 测试,没问题再 reload。

三、虚拟主机配置(跑多个网站)

每个网站一个配置文件,放在 /etc/nginx/sites-available/,软链接到 sites-enabled/:

sudo nano /etc/nginx/sites-available/blog.conf
server {
    listen 80;
    server_name blog.example.com;
    root /var/www/html;
    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.3-fpm.sock;
    }

    # 禁止访问敏感文件
    location ~ /\.ht {
        deny all;
    }
    location ~ /wp-content/database {
        deny all;
    }
}
sudo ln -s /etc/nginx/sites-available/blog.conf /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

四、反向代理

把请求转发给后端应用(比如跑在 3000 端口的 Node 服务):

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

    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;
    }
}

五、HTTPS 配置

用 Certbot 自动配置(详见《如何给网站加 HTTPS》):

sudo certbot --nginx -d blog.example.com

Certbot 会自动修改 Nginx 配置,加上 443 监听和证书路径。

六、常用优化

开启 Gzip 压缩

http {
    gzip on;
    gzip_types text/css application/javascript application/json;
}

限制上传大小

server {
    client_max_body_size 50M;
}

配置文件位置速查

  • 主配置:/etc/nginx/nginx.conf
  • 站点配置:/etc/nginx/sites-available/ 和 sites-enabled/
  • 访问日志:/var/log/nginx/access.log
  • 错误日志:/var/log/nginx/error.log

本文为杰哥的折腾笔记原创教程,转载请注明出处。

发表评论