Nginx 是一个高性能的 HTTP 和反向代理服务器,用于处理客户端请求并返回响应。它支持负载均衡、缓存、访问控制等功能,广泛应用于网站托管和流量管理。
Nginx 配置详解
Nginx 是一款开源、高性能的 HTTP 和反向代理服务器,具有负载均衡、静态资源服务以及反向代理等功能,它以高并发、高性能和低内存消耗著称,并且支持热部署,几乎可以做到不间断运行,以下是关于 Nginx 的一些基本配置示例。
一、基础配置
1、全局配置
user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid;
2、events 块
events { worker_connections 1024; }
3、http 块
http { 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 4096; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. include /etc/nginx/conf.d/*.conf; server { listen 80; server_name localhost; location / { root /usr/share/nginx/html; index index.html index.htm; } } }
二、常见模块配置
1、反向代理
server { listen 80; server_name alex.com; location / { proxy_pass http://backend-server; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }
2、负载均衡
upstream backend { server backend1.example.com weight=3; server backend2.example.com; server backend3.example.com; } server { listen 80; server_name example.com; 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; proxy_set_header X-Forwarded-Proto $scheme; } }
3、SSL 配置
server { listen 443 ssl; server_name example.com; ssl_certificate /path/to/your/certificate.crt; ssl_certificate_key /path/to/your/private-key.key; ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; location / { root /var/www/html; index index.html index.htm; } }
4、静态资源服务
server { listen 80; server_name static.example.com; location /static/ { alias /var/www/static/; access_log off; expires max; add_header Cache-Control public; } }
5、防盗链配置
location ~* .(gif|jpg|png)$ { valid_referers none blocked www.example.com; if ($invalid_referer) { return 403; } }
三、高级配置与优化
1、压缩传输
gzip on; gzip_comp_level 4; gzip_min_length 1000; gzip_proxied any; gzip_types text/plain application/xml text/css application/javascript;
2、限制请求速率
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s; server { location /search/ { limit_req zone=one burst=5; } }
3、缓存控制
location ~* .(css|js|jpg|jpeg|png|gif|ico)$ { expires 15d; access_log off; }
通过以上配置,可以实现 Nginx 的基本功能和一些常见的应用场景,根据实际需求,可以进一步调整和优化配置以达到最佳效果。
小伙伴们,上文介绍了“nginx配置”的内容,你了解清楚吗?希望对你有所帮助,任何问题可以给我留言,让我们下期再见吧。
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/1365471.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复