1. 引言
1.1 Nginx简介
Nginx(发音为 “engine-x”)是一款轻量级、高性能的HTTP服务器和反向代理服务器。它以其高并发处理能力和低资源消耗而闻名,广泛应用于互联网企业中。Nginx不仅可以作为静态文件服务器,还可以通过反向代理功能与后端应用服务器协同工作。
1.2 Nginx的应用场景
- Web服务器:托管静态文件(HTML、CSS、JavaScript等),并提供动态内容处理能力。
- 反向代理:将客户端请求转发给后端服务器,并将响应返回给客户端。
- 负载均衡:分发流量到多个后端服务器,提高系统可用性和性能。
- 缓存:加速静态内容的访问速度,减轻后端服务器的压力。
2. Nginx安装与基础配置
2.1 安装Nginx
2.1.1 在Linux上安装Nginx
在基于Debian/Ubuntu的系统上,可以通过以下命令安装:
sudo apt update
sudo apt install nginx
在基于RedHat/CentOS的系统上,可以通过以下命令安装:
sudo yum install epel-release
sudo yum install nginx
启动并启用Nginx服务:
sudo systemctl start nginx
sudo systemctl enable nginx
2.1.2 在Windows上安装Nginx(Docker方式)
首先确保已安装Docker Desktop。然后运行以下命令:
docker pull nginx
docker run --name mynginx -p 80:80 -d nginx
2.2 基础配置文件解析
Nginx的主要配置文件位于 /etc/nginx/nginx.conf
或 /usr/local/nginx/conf/nginx.conf
。以下是基础配置文件的结构:
nginx">user nginx;
worker_processes auto;error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;events {worker_connections 1024;
}http {include /etc/nginx/mime.types;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 /var/log/nginx/access.log main;sendfile on;tcp_nopush on;tcp_nodelay on;keepalive_timeout 65;types_hash_max_size 2048;include /etc/nginx/conf.d/*.conf;
}
常用指令说明:
worker_processes
:设置工作进程数,通常设置为CPU核心数。events
:定义事件模块的参数,如最大连接数。http
:定义HTTP服务器的行为,包括MIME类型、日志格式等。
2.3 启动与管理Nginx服务
使用以下命令启动、停止或重启Nginx服务:
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
3. 配置Nginx作为Web服务器
3.1 静态资源托管
3.1.1 搭建静态网站
创建一个简单的HTML页面并将其放置在Nginx默认的根目录 /usr/share/nginx/html
中。编辑配置文件 /etc/nginx/sites-available/default
或创建一个新的配置文件:
nginx">server {listen 80;server_name yourdomain.com;root /usr/share/nginx/html;index index.html;location / {try_files $uri $uri/ =404;}
}
重启Nginx以应用更改:
sudo systemctl restart nginx
3.1.2 文件缓存配置
为了提高静态文件的访问速度,可以启用缓存机制:
nginx">location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {expires 30d;add_header Cache-Control "public, no-transform";
}
3.2 动态内容处理
3.2.1 FastCGI与PHP集成
假设你已经安装了PHP-FPM,编辑Nginx配置文件以支持PHP:
nginx">server {listen 80;server_name yourdomain.com;root /var/www/html;index index.php index.html index.htm;location / {try_files $uri $uri/ =404;}location ~ \.php$ {