Nginx 安装与基本命令

6 阅读3分钟

一、 源码安装(以 CentOS 为例)

1、下载tar包

nginx.org/download/

下载 tar 包

wget nginx.org/download/ng…
tar -zxvf nginx-1.24.0.tar.gz
cd nginx-1.24.0

安装依赖

yum install -y pcre-devel zlib-devel openssl-devel

配置(指定安装目录及所需模块)

./configure --prefix=/home/program/nginx --with-http_stub_status_module --with-http_ssl_module

编译安装

make && make install

安装后目录结构:

/home/program/nginx/
├── conf/       # 配置文件
├── html/       # 默认静态页面
├── logs/       # 日志文件
└── sbin/       # 可执行文件(nginx)

2. 常用命令

# 启动
./sbin/nginx

# 快速停止
./sbin/nginx -s stop

# 优雅停止(处理完当前请求再停)
./sbin/nginx -s quit

# 重载配置(热部署)
./sbin/nginx -s reload

# 检查配置文件语法
./sbin/nginx -t

# 查看版本及编译参数
./sbin/nginx -V

 

启动后访问 http://服务器IP 看到欢迎页即成功。

二、Nginx 配置文件详解

nginx.conf 由三个主要块组成:

1.全局模块

设置影响 Nginx 整体运行的指令,如工作进程数、日志路径等。

user root;                # 运行用户
worker_processes 1;       # 工作进程数,建议等于 CPU 核心数
error_log logs/error.log error;
pid logs/nginx.pid;

2. events 块

配置网络连接相关参数。

events {
    worker_connections 1024;   # 每个工作进程最大连接数
    use epoll;                 # 事件驱动模型(Linux 推荐 epoll)
}

并发总数 ≈ worker_processes × worker_connections

3. http 块

最核心的部分,包含代理、缓存、日志格式、虚拟主机等配置。

http {
    include       mime.types;          # 文件扩展名与 MIME 类型映射
    default_type  application/octet-stream;
    
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
    access_log logs/access.log main;
    
    sendfile on;                # 高效文件传输
    keepalive_timeout 65;       # 长连接超时时间
    
    gzip on;                    # 启用压缩
    gzip_types text/css text/javascript application/javascript;
    
    # 虚拟主机配置
    server {
        listen 80;
        server_name localhost;
        location / {
            root html;
            index index.html index.htm;
        }
    }
}

 

三、虚拟主机配置

虚拟主机允许在一台物理服务器上运行多个网站,支持三种类型:

1. 基于端口

server {
    listen 8080;
    server_name localhost;
    location / {
        root html/port8080;
        index index.html;
    }
}

2. 基于 IP

server {
    listen 192.168.1.10:80;
    server_name iphost;
    location / {
        root html/iphost;
        index index.html;
    }
}

3. 基于域名(最常用)

server {
    listen 80;
    server_name www.example.com;
    location / {
        root html/www;
        index index.html;
    }
}
server {
    listen 80;
    server_name blog.example.com;
    location / {
        root html/blog;
        index blog.html;
    }
}

模块化管理:使用 include 指令将多个虚拟主机拆分到独立文件。

http {
    include extra/*.conf;   # 加载 extra 目录下所有 .conf 文件
}

四、Location 匹配规则(核心重点)

location 指令用于匹配请求 URI,决定如何处理请求。

语法

location [ = | ~ | ~* | ^~ ] uri { ... }

 

 

修饰符含义示例
=精确匹配,完全相等才匹配location = /index.html
^~前缀匹配,匹配后不再检查正则location ^~ /static/
~正则匹配,区分大小写location ~ .jpg$
~*正则匹配,不区分大小写location ~* .jpg$
普通字符串前缀匹配location /doc
/通用匹配,所有请求都命中location /

优先级(从高到低)

  1. 精确匹配 = → 立即使用,停止匹配
  2. 前缀匹配 ^~ → 匹配后不再检查正则
  3. 正则匹配 ~ 或 ~* → 按配置文件中的顺序,第一个匹配的生效
  4. 普通字符串前缀匹配 → 最长匹配优先
  5. 通用匹配 / → 兜底

示例演示

location = / {
    # 只匹配 http://domain/ 精确
}
location / {
    # 匹配所有请求,但优先级最低
}
location /documents/ {
    # 匹配以 /documents/ 开头的 URI
}
location ^~ /images/ {
    # 匹配 /images/ 开头,且不再检查正则
}
location ~* .(gif|jpg|jpeg)$ {
    # 匹配图片后缀,不区分大小写
}

  

实际匹配结果:

  • http://domain/ → 精确匹配 = /
  • http://domain/images/logo.png → ^~ /images/(不再匹配图片正则)
  • http://domain/photo.jpg → 正则 ~* .(gif|jpg|jpeg)$
  • http://domain/documents/readme.txt → 普通前缀 /documents/
  • http://domain/other → 通用 /

常用配置实践

# 静态资源缓存
location ~* .(gif|jpg|jpeg|png|css|js|ico)$ {
    expires 30d;
    root /data/static;
    access_log off;
}

# 精确匹配首页,快速响应
location = / {
    root /var/www/html;
    index index.html;
}

# API 反向代理
location /api/ {
    proxy_pass http://backend_server;
}

 

五、常用内置变量

Nginx 内置了许多变量,可在配置中直接使用(以 $ 开头)。

 

 

变量说明
$args请求参数(同 $query_string
$content_length请求头中的 Content-Length
$content_type请求头中的 Content-Type
$document_root当前请求的 root 指令值
$host请求的主机名
$http_user_agent客户端 User-Agent
$http_cookieCookie 信息
$remote_addr客户端 IP 地址
$remote_port客户端端口
$request_method请求方法(GET/POST 等)
$request_uri原始请求 URI(含参数)
$uri当前请求的 URI(不含参数)
$scheme协议(http 或 https)
$server_name服务器名称
$server_port服务器端口

 

使用示例:

location / {
    add_header X-Client-IP $remote_addr;
    add_header X-Request-URI $request_uri;
}

 

六、模块化与扩展

常见官方模块

  • ngx_http_stub_status_module:监控 Nginx 状态
  • ngx_http_random_index_module:随机首页
  • ngx_http_ssl_module:HTTPS 支持
  • ngx_http_rewrite_module:URL 重写

安装第三方模块(以 status 模块为例)

# 重新编译,带上已有模块和新模块
./configure --prefix=/home/program/nginx --with-http_stub_status_module
make
# 备份原 nginx 二进制,然后替换
cp objs/nginx /home/program/nginx/sbin/nginx

 

启用状态监控:

location /status {
    stub_status on;
    access_log off;
    allow 127.0.0.1;
    deny all;
}

 

访问 /status 即可看到活跃连接数等信息。

 

七、小结

本文带你全面认识了 Nginx:

  • 什么是 Nginx,它的核心优势
  • 正向代理、反向代理、负载均衡、动静分离的实战配置
  • 与 Apache、Tomcat 的区别及选型建议
  • 安装、目录结构、常用命令
  • 配置文件三大块(全局、events、http)
  • 虚拟主机(端口、IP、域名)
  • 最重要的 location 匹配规则与优先级
  • 内置变量与模块扩展

Nginx 的配置灵活且强大,掌握这些基础知识后,你可以继续深入学习:HTTPS 配置、Rewrite 重写、限流限速、缓存策略等。希望这篇博客成为你 Nginx 学习之路的坚实起点。