跳到主要内容
lanzai.co
返回

Nginx 安装与基础配置

Nginx 是高性能的 Web 服务器和反向代理。

安装

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

防火墙放行:

sudo ufw allow 'Nginx Full'

目录结构

/etc/nginx/
├── nginx.conf        # 主配置
├── sites-available/  # 站点配置(启用前的存放处)
└── sites-enabled/    # 启用的站点(软链接)

新增站点

/etc/nginx/sites-available/blog.conf:

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

    root /var/www/blog;
    index index.html;

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

启用并重载:

sudo ln -s /etc/nginx/sites-available/blog.conf /etc/nginx/sites-enabled/
sudo nginx -t          # 测试配置
sudo systemctl reload nginx

反向代理到本地服务

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

    location / {
        proxy_pass http://127.0.0.1:8080;
        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)

sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d blog.example.com
# 证书自动续期由 certbot renew 处理

常用运维

sudo systemctl status nginx      # 状态
sudo nginx -t                    # 配置测试
sudo tail -f /var/log/nginx/error.log

分享这篇文章:

上一篇
Docker 常用指令速查
下一篇
Linux 服务器常见问题排查