Nginx(发音为"engine x")是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP代理服务器。它以高并发、低内存占用著称,被广泛用于负载均衡、反向代理和静态资源服务。
# Ubuntu/Debian
sudo apt update
sudo apt install nginx
# CentOS/RHEL
sudo yum install epel-release
sudo yum install nginx
# 启动Nginx
sudo systemctl start nginx
# 停止Nginx
sudo systemctl stop nginx
# 重启Nginx
sudo systemctl restart nginx
# 重新加载配置(不中断服务)
sudo systemctl reload nginx
# 查看状态
sudo systemctl status nginx
# 设置开机启动
sudo systemctl enable nginx
Nginx的主要配置文件通常位于:
- /etc/nginx/nginx.conf
(Linux)
- conf/nginx.conf
(Windows)
配置文件主要由以下几部分组成: - 全局块:配置影响nginx全局的指令 - events块:配置影响nginx服务器或与用户的网络连接 - http块:可以嵌套多个server,配置代理,缓存,日志定义等绝大多数功能 - server块:配置虚拟主机的相关参数 - location块:配置请求的路由,以及各种页面的处理情况
# 全局配置
user www-data;
worker_processes auto;
pid /run/nginx.pid;
# 事件模块配置
events {
worker_connections 768;
}
# HTTP模块配置
http {
# 基础设置
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# MIME类型
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 日志格式
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
# 虚拟主机配置
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.html index.htm;
}
}
}
server {
listen 80;
server_name example.com;
location / {
root /var/www/example.com;
index index.html;
}
}
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
upstream backend {
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
}
}
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/ssl/certs/example.com.crt;
ssl_certificate_key /etc/ssl/private/example.com.key;
location / {
root /var/www/example.com;
index index.html;
}
}
location ~ /\. {
deny all;
}
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
error_page 404 /404.html;
location = /404.html {
root /var/www/errors;
internal;
}
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
server {
location /api/ {
limit_req zone=one burst=5;
proxy_pass http://api_server;
}
}
sudo nginx -t
ps aux | grep nginx
sudo netstat -tulpn | grep nginx
tail -f /var/log/nginx/error.log
通过这篇教程,你已经掌握了Nginx的基本安装、配置和使用方法。Nginx功能强大但配置灵活,建议从简单的静态网站服务开始,逐步尝试反向代理、负载均衡等高级功能。遇到问题时,多查看错误日志,使用nginx -t
测试配置语法,逐步调试解决问题。