插件窝 干货文章 Linux系统如何配置Nginx

Linux系统如何配置Nginx

Nginx 配置 example sudo 970    来源:    2025-04-27

Linux系统下Nginx配置指南

一、安装Nginx

Ubuntu/Debian系统

sudo apt update
sudo apt install nginx

CentOS/RHEL系统

sudo yum install epel-release
sudo yum install nginx

二、基本配置

1. 主要配置文件位置

  • 主配置文件: /etc/nginx/nginx.conf
  • 站点配置文件: /etc/nginx/conf.d//etc/nginx/sites-available/
  • 默认网站根目录: /usr/share/nginx/html

2. 常用命令

# 启动Nginx
sudo systemctl start nginx

# 停止Nginx
sudo systemctl stop nginx

# 重启Nginx
sudo systemctl restart nginx

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

# 设置开机启动
sudo systemctl enable nginx

# 检查配置语法
sudo nginx -t

三、配置虚拟主机

1. 创建站点配置文件

sudo nano /etc/nginx/conf.d/example.com.conf

2. 基本虚拟主机配置示例

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

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

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

    access_log /var/log/nginx/example.com.access.log;
    error_log /var/log/nginx/example.com.error.log;
}

四、HTTPS配置(使用Let's Encrypt)

1. 安装Certbot

# Ubuntu/Debian
sudo apt install certbot python3-certbot-nginx

# CentOS/RHEL
sudo yum install certbot python3-certbot-nginx

2. 获取并安装证书

sudo certbot --nginx -d example.com -d www.example.com

3. 自动续期测试

sudo certbot renew --dry-run

五、性能优化配置

1. 调整worker进程

worker_processes auto;  # 自动设置为CPU核心数
events {
    worker_connections 1024;  # 每个worker的最大连接数
    multi_accept on;  # 同时接受多个连接
}

2. 启用Gzip压缩

gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

3. 缓存设置

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

六、常见问题排查

  1. 检查Nginx状态: systemctl status nginx
  2. 查看错误日志: tail -f /var/log/nginx/error.log
  3. 测试配置: nginx -t
  4. 检查端口占用: netstat -tulnp | grep :80

七、高级配置

1. 反向代理配置

location /api/ {
    proxy_pass http://localhost: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;
}

2. 负载均衡配置

upstream backend {
    server backend1.example.com;
    server backend2.example.com;
    server backend3.example.com;
}

server {
    location / {
        proxy_pass http://backend;
    }
}

3. WebSocket支持

location /ws/ {
    proxy_pass http://backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

以上是Linux系统下Nginx的基本配置指南,根据实际需求可以进一步调整和优化配置。