销售:050-1791-1110

Nginx 基础配置

什么是 Nginx?

Nginx 是一个高性能的 Web 服务器和反向代理服务器,广泛用于托管网站、负载均衡和处理静态文件。

安装 Nginx

# Ubuntu/Debian
sudo apt update
sudo apt install nginx

# 启动并设为开机自启
sudo systemctl start nginx
sudo systemctl enable nginx

# 验证运行
sudo systemctl status nginx

基本配置文件结构

/etc/nginx/
├── nginx.conf           # 主配置文件
├── sites-available/     # 可用站点配置
├── sites-enabled/       # 已启用站点(符号链接)
├── conf.d/              # 额外配置片段
└── snippets/            # 可复用配置片段

创建站点配置

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

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

    # PHP 处理
    location ~ .php$ {
        include fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.3-fpm.sock;
    }

    # 禁止访问隐藏文件
    location ~ /. {
        deny all;
    }
}

启用站点

# 创建符号链接
sudo ln -s /etc/nginx/sites-available/mysite.conf /etc/nginx/sites-enabled/

# 检查配置语法
sudo nginx -t

# 重新加载
sudo systemctl reload nginx

反向代理配置

server {
    listen 80;
    server_name api.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;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

常用命令

sudo nginx -t              # 测试配置
sudo systemctl reload nginx # 重载配置
sudo systemctl restart nginx # 重启
sudo tail -f /var/log/nginx/error.log  # 查看错误日志
滚动至顶部