插件窝 干货文章 Nginx简要安装配置实例分析

Nginx简要安装配置实例分析

Nginx 配置 sudo log 647    来源:    2025-04-23

以下是一个Nginx的简明安装配置指南及实例分析,适用于Linux环境(以Ubuntu为例):


1. 安装Nginx

# Ubuntu/Debian
sudo apt update
sudo apt install nginx -y

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

安装后验证服务状态:

sudo systemctl start nginx
sudo systemctl enable nginx
sudo systemctl status nginx

2. 关键目录结构

  • 配置文件目录/etc/nginx/
    • 主配置文件:nginx.conf
    • 子配置目录:/etc/nginx/conf.d//etc/nginx/sites-enabled/
  • 默认网站根目录/var/www/html
  • 日志文件/var/log/nginx/access.logerror.log

3. 基础配置示例

场景1:静态网站托管

编辑配置文件(如 /etc/nginx/conf.d/static_site.conf):

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

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

    # 日志配置
    access_log /var/log/nginx/static_access.log;
    error_log /var/log/nginx/static_error.log;
}

场景2:反向代理(代理到本地应用)

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

    location / {
        proxy_pass http://localhost:3000;  # 转发到本地的Node.js应用
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

4. 常用操作命令

# 测试配置语法
sudo nginx -t

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

# 彻底停止并重启
sudo systemctl restart nginx

5. 安全优化建议

  1. 禁用服务器版本信息
    nginx.confhttp 块中添加:

    server_tokens off;
    
  2. 限制HTTP方法

    location / {
       limit_except GET POST { deny all; }
    }
    
  3. 启用HTTPS(使用Let's Encrypt):

    sudo apt install certbot python3-certbot-nginx
    sudo certbot --nginx -d example.com
    

6. 故障排查技巧

  • 检查日志

    tail -f /var/log/nginx/error.log
    
  • 检查端口占用

    sudo netstat -tulnp | grep :80
    
  • 详细调试模式
    在配置中增加 error_log /var/log/nginx/debug.log debug;


7. 性能调优参数示例

nginx.confevents 块中调整:

worker_processes auto;  # 自动匹配CPU核心数
events {
    worker_connections 1024;  # 单个worker最大连接数
    multi_accept on;
}

通过以上步骤,您可以快速部署和配置Nginx以满足常见需求。根据实际场景调整参数(如缓存、负载均衡等)可进一步优化性能。