一、安装 Nginx

1. CentOS / RHEL 系

bashbash复制# 1. 添加 EPEL 源(如果系统没有)sudo yum install epel-release -y# 2. 安装 Nginxsudo yum install nginx -y# 3. 启动并设置开机自启sudo systemctl start nginxsudo systemctl enable nginx

检查状态:

bashbash复制sudo systemctl status nginx

看到 active (running)就说明服务已正常启动。

2. Ubuntu / Debian 系

bashbash复制# 1. 更新软件包索引sudo apt update# 2. 安装 Nginxsudo apt install nginx -y# 3. 启动并设置开机自启sudo systemctl start nginxsudo systemctl enable nginx

检查:

bashbash复制sudo systemctl status nginx

二、验证是否安装成功

在服务器本机或同网段机器浏览器访问:

复制http://服务器IP地址/

能看到 Nginx 默认欢迎页,说明 Web 服务本身没问题。

三、Nginx 配置文件结构与语法

1. 配置文件目录概览(以常见路径为例)

  • /etc/nginx/nginx.conf主配置文件


  • /etc/nginx/conf.d/:存放 .conf后缀的站点配置(推荐用法)


  • /usr/share/nginx/html/:默认网页根目录(CentOS)


  • /var/www/html/:Ubuntu 常见网页根目录


主配置文件里一般会有一行类似:

nginxnginx复制include /etc/nginx/conf.d/*.conf;

这表示会把 conf.d/目录下所有 .conf文件加载进来。

2. 最小可用站点配置示例

新建一个站点配置:/etc/nginx/conf.d/myapp.conf

nginxnginx复制server {    listen       80;
    server_name  example.com www.example.com;    # 网站根目录(按实际改)
    root   /var/www/myapp;    index  index.html index.htm;

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

要点说明:

  • listen 80;:监听 HTTP 80 端口;


  • server_name:匹配的域名;


  • root:静态文件根目录;


  • location /:匹配所有请求,try_files按顺序查找文件是否存在。


3. 重载配置使其生效

每次修改配置后执行:

bashbash复制sudo nginx -t       # 语法检查,输出 "syntax is ok" 才可继续sudo systemctl reload nginx   # 平滑重载配置

四、常用场景配置示例

1. 反向代理到后端应用(如 Node.js / Java)

假设后端跑在本机 127.0.0.1:3000

nginxnginx复制server {    listen       80;
    server_name  api.example.com;

    location / {
        proxy_pass         http://127.0.0.1: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. 启用 Gzip 压缩提升传输效率

在主配置文件 nginx.confhttp {}块中加入:

nginxnginx复制gzip on;
gzip_types text/plain text/css application/json application/javascript;
gzip_min_length 1024;

3. 简单访问控制(限制 IP)

nginxnginx复制location /admin/ {
    allow 192.168.1.100;
    deny all;
}

五、防火墙放行 HTTP/HTTPS

CentOS / RHEL(firewalld)

bashbash复制sudo firewall-cmd --permanent --add-service=httpsudo firewall-cmd --permanent --add-service=httpssudo firewall-cmd --reload

Ubuntu(ufw)

bashbash复制sudo ufw allow 'Nginx Full'

六、常见问题排查

  • 无法访问:


    • 看 Nginx 是否运行:systemctl status nginx


    • 看端口是否监听:ss -ltnp | grep nginx


    • 看防火墙/云安全组是否放通 80/443


  • 配置不生效:


    • nginx -t检查语法


    • systemctl reload nginx重载


  • 403 Forbidden:


    • 检查 root路径是否存在


    • 检查目录/文件权限,Nginx 进程需要可读


需要我针对某个具体场景(比如:多站点配置、SSL 证书、负载均衡)帮你写一份更完整的配置模板吗?