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!
Are you sure that proxy_set_header Host $host
doesn't change anything? According to the documentation:
When the use of the primary server name is disabled, the name from the “Host” request header field is used
Since server_name_in_redirect
is off
by default, nginx should emit 301 redirect with a hostname from the Host header.
Anyway, it's a halfway solution as the proxied server don't know that it is behind TLS termination proxy and thus should return https redirect. With your configuration it should still work, but with two redirects — the first one by the proxied server (https without slash → http with slash), and the second one by the proxy (http with slash → https with slash).
The easiest way to fix it is to use absolute_redirect off
in the proxied server (the one that serve static files): https://nginx.org/en/docs/http/ngx_http_core_module.html#absolute_redirect