参考答案:
Nginx是一款高性能的HTTP服务器和反向代理服务器,以其轻量级、高并发和灵活性著称。在现代网络架构中,Nginx有许多最佳用途,涵盖了静态资源服务、反向代理、负载均衡等多个场景。
gzip
)和浏览器缓存,优化静态资源加载速度。1server { 2 listen 80; 3 server_name example.com; 4 5 location / { 6 root /var/www/html; 7 index index.html; 8 } 9 10 # 开启gzip压缩 11 gzip on; 12 gzip_types text/plain text/css application/json application/javascript; 13}
1server { 2 listen 80; 3 server_name api.example.com; 4 5 location / { 6 proxy_pass http://127.0.0.1:8080; # 转发到后端应用 7 proxy_set_header Host $host; # 保留Host头信息 8 proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=cache:10m inactive=60m; 9 } 10}
1upstream backend { 2 least_conn; # 使用最少连接策略 3 server 192.168.1.101; 4 server 192.168.1.102; 5 server 192.168.1.103; 6} 7 8server { 9 listen 80; 10 server_name www.example.com; 11 12 location / { 13 proxy_pass http://backend; 14 } 15}
1server { 2 listen 80; 3 server_name api.example.com; 4 5 # 转发API请求到不同的服务 6 location /service1/ { 7 proxy_pass http://127.0.0.1:8081; 8 } 9 10 location /service2/ { 11 proxy_pass http://127.0.0.1:8082; 12 } 13}
Certbot
等工具结合)。1server { 2 listen 443 ssl; 3 server_name secure.example.com; 4 5 ssl_certificate /etc/nginx/ssl/example.com.crt; 6 ssl_certificate_key /etc/nginx/ssl/example.com.key; 7 8 location / { 9 proxy_pass http://127.0.0.1:8080; 10 } 11}
1proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m; 2server { 3 listen 80; 4 5 location / { 6 proxy_cache my_cache; 7 proxy_pass http://127.0.0.1:8080; 8 add_header X-Cache-Status $upstream_cache_status; 9 } 10}
1server { 2 listen 443 ssl http2; 3 server_name example.com; 4 5 ssl_certificate /etc/nginx/ssl/example.com.crt; 6 ssl_certificate_key /etc/nginx/ssl/example.com.key; 7}
Upgrade
和Connection
头)。1server { 2 listen 80; 3 server_name ws.example.com; 4 5 location /ws/ { 6 proxy_pass http://127.0.0.1:8080; 7 proxy_http_version 1.1; 8 proxy_set_header Upgrade $http_upgrade; 9 proxy_set_header Connection "upgrade"; 10 } 11}
1server { 2 listen 80; 3 4 # 静态资源 5 location /static/ { 6 root /var/www/html; 7 } 8 9 # 动态请求 10 location / { 11 proxy_pass http://127.0.0.1:8080; 12 } 13}
ModSecurity
)实现Web应用防火墙(WAF)功能。最近更新时间:2024-12-23