Nginx可以通过以下几种方法实现动静分离:
- 通过文件类型进行分离:在Nginx配置文件中,可以使用
location
指令来根据文件类型进行分离。例如,可以将静态文件的请求(如图片、CSS、JS)转发到一个静态文件服务器,而其他动态请求则转发到应用服务器。示例配置如下:
server { listen 80; server_name example.com; location /static { alias /path/to/static/files; } location / { proxy_pass http://backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } location ~* \.(jpg|jpeg|png|gif|css|js)$ { expires 1y; access_log off; root /path/to/static/files; } location ~ \.php$ { proxy_pass http://backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } }
- 根据URL路径进行分离:可以根据URL路径的前缀来进行动静分离。例如,可以将以
/static/
开头的URL请求转发到静态文件服务器,而其他请求则转发到应用服务器。示例配置如下:
server { listen 80; server_name example.com; location /static { proxy_pass http://static_server; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } location / { proxy_pass http://backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } }
- 使用反向代理缓存:Nginx还可以使用反向代理缓存来实现动静分离。可以将经常访问的静态资源缓存到Nginx服务器上,并设置合适的缓存时间。示例配置如下:
http { proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m; server { listen 80; server_name example.com; location /static { proxy_cache my_cache; proxy_cache_valid 200 1d; proxy_cache_use_stale error timeout updating http_500 http_503 http_504; proxy_ignore_headers Set-Cookie; proxy_hide_header Set-Cookie; proxy_pass http://backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } location / { proxy_pass http://backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } }
上述配置中,proxy_cache_path
指定了缓存存储路径和相关配置,proxy_cache
指定了使用的缓存区域,proxy_cache_valid
指定了缓存的有效期,proxy_cache_use_stale
指定了在缓存失效时的行为,proxy_ignore_headers
和proxy_hide_header
用于处理缓存相关的响应头。