nginxで静動分離を実現する方法
Nginxによる動静分離は次のように実現できます。
- 住所
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;
}
}
- この文章を日本語に直訳すると、
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はキャッシュに関連する応答ヘッダーの処理に使用されます。