跳到主要内容

Nginx Server 配置

介绍

Nginx 是一个高性能的 Web 服务器和反向代理服务器,广泛用于处理静态资源、负载均衡和反向代理等任务。在 Nginx 中,server 块是配置虚拟主机的核心部分。每个 server 块定义了如何处理特定域名或 IP 地址的请求。

本文将逐步讲解如何配置 Nginx 的 server 块,并通过实际案例帮助你理解其应用场景。

基本结构

一个典型的 server 块配置如下:

nginx
server {
listen 80;
server_name example.com;

location / {
root /var/www/html;
index index.html;
}
}

解释

  • listen:指定服务器监听的端口号。例如,listen 80; 表示监听 HTTP 请求的默认端口 80。
  • server_name:定义服务器响应的域名。例如,server_name example.com; 表示该 server 块仅处理 example.com 的请求。
  • location:定义如何处理特定路径的请求。例如,location / 表示处理根路径的请求。
  • root:指定静态文件的根目录。例如,root /var/www/html; 表示静态文件存放在 /var/www/html 目录下。
  • index:指定默认的索引文件。例如,index index.html; 表示当访问根路径时,默认返回 index.html 文件。

配置多个虚拟主机

Nginx 支持在同一台服务器上配置多个虚拟主机。每个虚拟主机可以通过不同的 server_name 来区分。

nginx
server {
listen 80;
server_name example.com;

location / {
root /var/www/example;
index index.html;
}
}

server {
listen 80;
server_name another-example.com;

location / {
root /var/www/another-example;
index index.html;
}
}

解释

  • 第一个 server 块处理 example.com 的请求,静态文件存放在 /var/www/example 目录下。
  • 第二个 server 块处理 another-example.com 的请求,静态文件存放在 /var/www/another-example 目录下。

处理不同路径的请求

location 块可以用于处理不同路径的请求。以下是一个处理多个路径的示例:

nginx
server {
listen 80;
server_name example.com;

location / {
root /var/www/html;
index index.html;
}

location /images/ {
root /var/www;
}

location /api/ {
proxy_pass http://localhost:3000/;
}
}

解释

  • location /:处理根路径的请求,返回 /var/www/html 目录下的 index.html 文件。
  • location /images/:处理 /images/ 路径的请求,返回 /var/www/images 目录下的文件。
  • location /api/:将 /api/ 路径的请求转发到本地端口 3000 的服务。

实际案例

假设你有一个网站 example.com,并且希望实现以下功能:

  1. 主站点的静态文件存放在 /var/www/html 目录下。
  2. /blog 路径的请求转发到另一个服务器 http://localhost:4000
  3. /images 路径的请求返回 /var/www/images 目录下的文件。

配置如下:

nginx
server {
listen 80;
server_name example.com;

location / {
root /var/www/html;
index index.html;
}

location /blog {
proxy_pass http://localhost:4000;
}

location /images {
root /var/www;
}
}

解释

  • 访问 example.com 时,返回 /var/www/html 目录下的 index.html 文件。
  • 访问 example.com/blog 时,请求被转发到 http://localhost:4000
  • 访问 example.com/images 时,返回 /var/www/images 目录下的文件。

总结

通过本文,你学习了如何配置 Nginx 的 server 块,包括定义虚拟主机、处理不同路径的请求以及转发请求到其他服务器。Nginx 的 server 配置非常灵活,能够满足各种复杂的 Web 服务器需求。

附加资源

练习

  1. 配置一个 Nginx server 块,使其监听端口 8080,并处理 test.com 的请求。
  2. server 块中添加一个 location,将 /api 路径的请求转发到 http://localhost:5000
  3. 配置多个虚拟主机,分别处理 site1.comsite2.com 的请求。

通过完成这些练习,你将更深入地理解 Nginx 的 server 配置。