插件窝 干货文章 Linux服务器下该怎么安装配置Nginx

Linux服务器下该怎么安装配置Nginx

Nginx 配置 sudo example 450    来源:    2025-04-21

在Linux服务器上安装和配置Nginx可以分为以下几个步骤,我将以CentOS/RHEL和Ubuntu/Debian两种主流系统为例进行说明:


一、安装Nginx

1. CentOS/RHEL系统

# 添加EPEL仓库(针对CentOS/RHEL 7/8)
sudo yum install epel-release

# 安装Nginx
sudo yum install nginx

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

2. Ubuntu/Debian系统

# 更新软件包列表
sudo apt update

# 安装Nginx
sudo apt install nginx

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

二、基础配置

1. 检查Nginx状态

sudo systemctl status nginx

如果看到"active (running)"表示服务已启动。

2. 防火墙放行HTTP/HTTPS

# CentOS/RHEL (firewalld)
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

# Ubuntu/Debian (ufw)
sudo ufw allow 'Nginx Full'

3. 测试访问

浏览器访问 http://服务器IP,看到Nginx欢迎页即表示安装成功。


三、配置文件结构

Nginx的核心配置文件位于: - 主配置文件:/etc/nginx/nginx.conf - 站点配置:/etc/nginx/conf.d//etc/nginx/sites-available/ - 默认网站根目录:/usr/share/nginx/html


四、配置虚拟主机(示例)

以域名 example.com 为例:

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;
}

3. 创建网站目录并授权

sudo mkdir -p /var/www/example.com/html
sudo chown -R $USER:$USER /var/www/example.com/html
sudo chmod -R 755 /var/www

4. 创建测试页面

echo "<h1>Welcome to example.com</h1>" > /var/www/example.com/html/index.html

5. 测试配置并重载

sudo nginx -t   # 测试配置语法
sudo systemctl reload nginx

五、进阶配置

1. 启用HTTPS(Let's Encrypt)

# 安装Certbot工具
# CentOS/RHEL:
sudo yum install certbot python3-certbot-nginx

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

# 获取证书并自动配置
sudo certbot --nginx -d example.com -d www.example.com

证书会自动续期,配置保存在 /etc/letsencrypt/

2. 反向代理配置

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

3. 负载均衡(示例)

upstream backend {
    server 192.168.1.10:80;
    server 192.168.1.11:80;
}

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

六、常用命令

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

# 测试配置文件
sudo nginx -t

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

七、日志查看

  • 访问日志:/var/log/nginx/access.log
  • 错误日志:/var/log/nginx/error.log
  • 实时监控:sudo tail -f /var/log/nginx/access.log

注意事项

  1. 修改配置后务必用 nginx -t 测试语法。
  2. 生产环境建议禁用服务器版本号: nginx server_tokens off;
  3. 对于高并发场景,需调整 worker_processesworker_connections 参数。

如果需要更具体的配置(如缓存、Gzip、安全头等),可以进一步扩展配置内容。