在实现nginx动静分离时,需要将静态文件和动态请求进行分离,可以通过以下配置实现:
1. 静态文件配置:
location /static/ {root /path/to/static/files;expires 7d;access_log off;
}location /media/ {root /path/to/media/files;expires max;access_log off;
}
上述配置会将以 `/static/` 开头的URL请求映射到 `/path/to/static/files` 目录下的静态文件,并设置缓存时间为7天。类似地,以 `/media/` 开头的URL请求会映射到 `/path/to/media/files` 目录下的文件,并设置缓存时间为最大值。
2. 动态请求配置:
location / {proxy_pass http://127.0.0.1:8000; # 将动态请求转发到后端服务器proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;
}
上述配置会将所有非静态文件请求转发到后端服务器(例如在本例中是转发到 `127.0.0.1:8000`)。需要根据实际情况修改 `proxy_pass` 的值为后端服务器的地址。
将上述配置添加到nginx的配置文件中,并重新加载nginx配置后,即可实现nginx的动静分离。静态文件会由nginx直接返回,而动态请求会被转发到后端服务器处理。