# Server 与 Location 块配置

URL: https://caijiao.org/nginx/server-and-location
Source: docs/nginx/server-and-location.md
Description: 本节介绍 Nginx 配置文件中的 server 与 location 块，用于配置虚拟主机、端口、域名及请求路由规则，帮助你理解 nginx.conf 中的站点管理与请求处理。

server 和 location 块用于定义虚拟主机和请求路由，是 Nginx 配置文件中最核心的 HTTP 层面部分。

## 一、server 块基本结构

```nginx
server {
    listen       80;
    server_name  www.example.com example.com;
    
    root   /var/www/html;
    index  index.html index.htm index.php;

    access_log  /var/log/nginx/example.access.log  main;
    error_log   /var/log/nginx/example.error.log warn;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}
````

### server 块指令说明

* **listen**：监听端口，可指定 IP
* **server_name**：匹配访问域名
* **root**：站点根目录
* **index**：默认首页文件
* **access_log / error_log**：独立站点日志
* **location**：请求路由规则

## 二、location 块用法

location 块用于匹配请求 URI，并执行相应操作：

### 1. 精确匹配

```nginx
location = /index.html {
    root /var/www/html;
}
```

### 2. 前缀匹配

```nginx
location /images/ {
    root /var/www/html;
}
```

### 3. 正则匹配

```nginx
location ~ \.php$ {
    fastcgi_pass 127.0.0.1:9000;
}
```

### 4. 常用指令

* **try_files**：尝试按顺序查找文件，找不到返回 404
* **include fastcgi_params**：加载 FastCGI 参数
* **fastcgi_pass**：指定 PHP-FPM 服务地址
* **fastcgi_param SCRIPT_FILENAME**：传递脚本文件路径

## 三、Server 与 Location 块优化建议

1. 使用 server_name 精确匹配域名，避免默认站点冲突
2. 对静态文件使用前缀匹配 location，提高访问效率
3. 对 PHP 或其他后端服务使用正则匹配，并通过 fastcgi_pass 转发
4. 日志分离，便于站点分析和排查问题

---

通过掌握 server 与 location 块，你可以灵活配置虚拟主机和请求路由，实现多站点部署及动态内容处理。
