插件窝 干货文章 Nginx如何安装配置

Nginx如何安装配置

Nginx sudo 配置 log 868    来源:    2025-04-27

以下是详细的Nginx安装配置指南,涵盖主流操作系统和关键配置步骤:


一、安装Nginx

1. Linux系统(以Ubuntu/CentOS为例)

# Ubuntu/Debian
sudo apt update
sudo apt install nginx

# CentOS/RHEL
sudo yum install epel-release
sudo yum install nginx

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

2. macOS(通过Homebrew)

brew install nginx
brew services start nginx

3. Windows

  • 从官网下载Windows版压缩包:nginx.org/download
  • 解压后双击 nginx.exe 启动(或通过命令行操作)。

二、基础配置

1. 配置文件结构

  • 主配置文件:/etc/nginx/nginx.conf(Linux)或 conf/nginx.conf(Windows)
  • 站点配置:通常放在 /etc/nginx/sites-available/(需软链接到 /etc/nginx/sites-enabled/

2. 配置静态网站

server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/html;
    index index.html;

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

3. 反向代理配置

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

    location / {
        proxy_pass http://localhost:3000;  # 转发到本地3000端口
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

4. 启用HTTPS(Let's Encrypt)

# 安装Certbot(Ubuntu为例)
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com
  • 自动更新证书:sudo certbot renew --dry-run

三、常用命令

# 检查配置语法
sudo nginx -t

# 重新加载配置(不中断服务)
sudo nginx -s reload

# 停止/重启
sudo systemctl stop nginx
sudo systemctl restart nginx

四、性能优化建议

  1. Worker进程数(根据CPU核心数调整): nginx worker_processes auto;
  2. 连接数限制nginx events { worker_connections 1024; }
  3. 启用Gzip压缩nginx gzip on; gzip_types text/css application/json;

五、日志管理

  • 访问日志:/var/log/nginx/access.log
  • 错误日志:/var/log/nginx/error.log
  • 自定义日志格式: nginx log_format custom '$remote_addr - $request_time'; access_log /var/log/nginx/access.log custom;

六、故障排查

  1. 端口占用bash sudo lsof -i :80
  2. 权限问题bash sudo chown -R www-data:www-data /var/www/html
  3. 查看实时错误bash sudo tail -f /var/log/nginx/error.log

通过以上步骤,您可以快速部署和优化Nginx。根据实际需求调整配置,如负载均衡、缓存等高级功能可进一步扩展。