温馨提示×

如何配置linux nginx

小樊
43
2026-10-29 03:10:13
栏目: 智能运维

下面给你一份从零开始配置 Linux 上 Nginx的实用指南,涵盖安装 → 基础配置 → 常见场景 → 常用命令。


一、安装 Nginx(常见 Linux 发行版)

1. CentOS / Rocky / AlmaLinux

sudo yum install epel-release -y
sudo yum install nginx -y

2. Ubuntu / Debian

sudo apt update
sudo apt install nginx -y

3. 启动并设置开机自启

sudo systemctl start nginx
sudo systemctl enable nginx

验证:

systemctl status nginx

浏览器访问服务器 IP,看到 Welcome to nginx 即成功。


二、Nginx 配置文件结构

主要配置文件

/etc/nginx/nginx.conf          # 主配置
/etc/nginx/conf.d/*.conf       # 自定义站点配置(推荐)
/etc/nginx/sites-enabled/      # Ubuntu 常用

最小可用结构

user nginx;
worker_processes auto;

events {
    worker_connections 1024;
}

http {
    include mime.types;
    server {
        listen 80;
        server_name example.com;

        location / {
            root /usr/share/nginx/html;
            index index.html;
        }
    }
}

三、配置一个静态网站

1. 创建网站目录

sudo mkdir -p /var/www/example
sudo echo "Hello Nginx" > /var/www/example/index.html

2. 新建配置文件

sudo vim /etc/nginx/conf.d/example.conf
server {
    listen 80;
    server_name example.com www.example.com;

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

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

3. 检查并重载

sudo nginx -t
sudo systemctl reload nginx

四、配置反向代理(最常见)

代理到后端(如 Java / Node / Python)

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

    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

五、HTTPS(SSL)配置(推荐)

1. 安装 certbot

# Ubuntu
sudo apt install certbot python3-certbot-nginx -y

# CentOS
sudo yum install certbot python3-certbot-nginx -y

2. 自动申请并配置

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

3. 自动续期测试

sudo certbot renew --dry-run

六、常用 Nginx 命令

nginx -t                 # 检查配置
systemctl start nginx   # 启动
systemctl stop nginx    # 停止
systemctl reload nginx  # 平滑重载
systemctl restart nginx # 重启

七、常见排错

端口被占用

sudo netstat -tunlp | grep 80

防火墙

# CentOS
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

# Ubuntu
sudo ufw allow 80
sudo ufw allow 443

权限问题

chown -R nginx:nginx /var/www/example

八、你下一步可以做什么?

  • 配置 负载均衡
  • 配置 Gzip / 缓存
  • 配置 访问日志 / 限流
  • 配置 WebSocket 反向代理

如果你告诉我: ✅ Linux 发行版
✅ 用途(静态站 / 接口 / 前端 / 后端)
✅ 是否用域名 / HTTPS

我可以直接帮你写完整可用的 nginx 配置。

0 踩