动静分离是一种常见的Web优化技术,通过将动态内容和静态内容分开处理,可以显著提高网站性能。以下是Nginx实现动静分离的详细配置方法:
server {
listen 80;
server_name example.com;
# 静态资源处理
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
root /var/www/static;
expires 30d;
access_log off;
add_header Cache-Control "public";
}
# 动态请求处理
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;
}
}
更彻底的分离方式是使用不同的域名:
# 静态资源服务器配置
server {
listen 80;
server_name static.example.com;
root /var/www/static;
location / {
expires max;
add_header Cache-Control "public";
access_log off;
}
}
# 动态内容服务器配置
server {
listen 80;
server_name www.example.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;
}
}
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_comp_level 6;
gzip_min_length 1000;
gzip_proxied any;
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
root /var/www/static;
expires 1y;
add_header Cache-Control "public, immutable";
# 启用ETag
etag on;
}
upstream static_servers {
server static1.example.com;
server static2.example.com;
}
upstream app_servers {
server app1.example.com;
server app2.example.com;
}
server {
location /static/ {
proxy_pass http://static_servers;
}
location / {
proxy_pass http://app_servers;
}
}
配置完成后,可以通过以下方式验证:
Cache-Control
和Expires
通过以上配置,您可以有效实现Nginx的动静分离,显著提升网站性能。