I’m new to ngnix. I’m trying to use nginx cache for static files in server.
nginx configuration for that specific server in http
block:
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=static_cache:10m max_size=5g inactive=60m use_temp_path=off;
upstream backend {
server 127.0.0.1:8000; # Localhost
}
server {
listen 8000;
root /var/www/html;
index index.html;
server_name _;
location / {
try_files $uri $uri/ =404;
}
}
server {
server_name example.com;
location / {
proxy_set_header Host $host; # or even proxy_set_header Host example.com
proxy_pass http://backend/;
proxy_cache static_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
add_header X-Cache-Status $upstream_cache_status;
proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
}
listen 443 ssl;
ssl_certificate /path/to/../fullchain.pem;
ssl_certificate_key /path/to/../privkey.pem;
include /path/to/../options-ssl-nginx.conf;
ssl_dhparam /path/to/../ssl-dhparams.pem
}
server {
if ($host = example.com) {
return 301 https://$host$request_uri;
}
listen 80;
server_name example.com;
return 404;
}
after setting this configuration everything worked fine for nginx cache, but there was a problem with urls where had index.html in them.
when we called something like https://example.com/static/folder
without /
the url in browser turns to http://backend:8000/static/folder/
but if call the url with /
like http://example.com/static/folder/
, it returns the page without any problem and the url would be https://example.com/static/folder/
.
I want to know how to fix this behaviour or if there is any better solution for caching in nginx here.
i tried to define Host like:
proxy_set_header Host $host; # or even proxy_set_header Host example.com
but it didn’t change anything!