插件窝 干货文章 如何部署Nginx服务

如何部署Nginx服务

Nginx 配置 sudo systemctl 767    来源:    2025-04-27

Nginx服务部署指南

Nginx是一款高性能的HTTP和反向代理服务器,以下是详细的部署步骤:

1. 安装Nginx

Linux系统安装

# Ubuntu/Debian
sudo apt update
sudo apt install nginx

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

# 验证安装
nginx -v

Windows系统安装

  1. Nginx官网下载Windows版本
  2. 解压到指定目录
  3. 运行nginx.exe

2. 基本配置

主要配置文件位置

  • 主配置文件: /etc/nginx/nginx.conf
  • 站点配置文件: /etc/nginx/conf.d//etc/nginx/sites-available/

常用命令

# 启动
sudo systemctl start nginx

# 停止
sudo systemctl stop nginx

# 重启
sudo systemctl restart nginx

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

# 设置开机启动
sudo systemctl enable nginx

3. 配置示例

基本HTTP服务器配置

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

    root /var/www/example.com;
    index index.html index.htm;

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

反向代理配置

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

    location / {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

4. 安全配置建议

  1. 禁用服务器标记:

    server_tokens off;
    
  2. 配置SSL/TLS:

    server {
       listen 443 ssl;
       server_name example.com;
    
       ssl_certificate /path/to/cert.pem;
       ssl_certificate_key /path/to/key.pem;
    
       # 其他SSL配置...
    }
    
  3. 限制HTTP方法:

    location / {
       limit_except GET POST {
           deny all;
       }
    }
    

5. 性能优化

  1. 启用Gzip压缩:

    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml;
    
  2. 调整工作进程:

    worker_processes auto; # 通常设置为CPU核心数
    
  3. 连接数限制:

    events {
       worker_connections 1024;
    }
    

6. 日志管理

  • 访问日志: /var/log/nginx/access.log
  • 错误日志: /var/log/nginx/error.log

可以自定义日志格式:

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" "$http_x_forwarded_for"';

7. 常见问题排查

  1. 测试配置语法:

    sudo nginx -t
    
  2. 检查运行状态:

    sudo systemctl status nginx
    
  3. 检查端口占用:

    sudo netstat -tulnp | grep :80
    

按照以上步骤,您应该能够成功部署和配置Nginx服务。根据实际需求调整配置参数以获得最佳性能。