一、安装部署
1、安装
# 在Ubuntu上安装Nginx sudo apt-get update sudo apt-get install nginx
2、配置Nginx
# Nginx配置文件路径:/etc/nginx/nginx.conf http { ... server { listen 80; server_name localhost; ... } }
3、启动Nginx
# 启动Nginx sudo systemctl start nginx # 停止Nginx sudo systemctl stop nginx # 重新加载配置文件 sudo systemctl reload nginx
二、反向代理与负载均衡
1、反向代理
# 配置反向代理 http { ... upstream backend { server backend1.example.com; server backend2.example.com; server backend3.example.com; } server { listen 80; server_name localhost; location / { proxy_pass http://backend; } } }
2、负载均衡
# 配置负载均衡 http { ... upstream backend { server backend1.example.com; server backend2.example.com; server backend3.example.com; } server { listen 80; server_name localhost; location / { proxy_pass http://backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } }
三、静态文件服务
1、配置静态文件服务
# 配置静态文件服务 http { ... server { listen 80; server_name localhost; location / { root /path/to/your/website; index index.html index.htm; } } }
2、配置缓存
# 配置缓存 http { ... server { listen 80; server_name localhost; location / { root /path/to/your/website; index index.html index.htm; expires 1d; } } }
四、安全加固
1、访问控制
# 配置访问控制 http { ... server { listen 80; server_name localhost; # 不允许通过ip地址直接访问 location / { deny all; } # 允许某个ip地址访问 location /private/ { allow 192.168.1.100; deny all; } } }
2、SSL配置
# 配置SSL http { ... server { listen 443 ssl; ssl_certificate /path/to/your_certificate.pem; ssl_certificate_key /path/to/your_private_key.pem; location / { root /path/to/your/website; index index.html index.htm; } } }
五、Websocket支持
1、配置Websocket支持
# 配置Websocket http { ... map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 80; server_name localhost; location / { proxy_pass http://backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } location /ws { proxy_pass http://backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } } }
六、本地开发
1、配置本地开发环境
# 配置本地开发环境 http { ... server { listen 80; server_name localhost; # 静态文件服务 location /static/ { alias /path/to/your/static/files; } # API代理 location /api/ { proxy_pass http://backend; } # WebSocket代理 location /ws/ { proxy_pass http://backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } } }
七、小结
nginx是一款高性能的Web服务器,常用于静态文件服务、反向代理、负载均衡、Websocket支持等场景,同时也能进行安全加固并配置本地开发环境。以上是nginx经典教程的详细解释,仅供参考。