I'm trying a simple location
directive in my nginx config, and it doesn't seem to be working all that well; I want to ensure that all requests to a local css or js file have an expires header, so I added the following to my server block (shown below). Am I missing something? The movies
location block correctly works (and loads CSS), however it does not have the expires header as expected. I've tried putting the wanted location block inside the movies
location block to no success.
server {
server_name www.example.com;
index index.php index.html index.htm;
access_log /var/log/nginx/example.com/access.log;
error_log /var/log/nginx/example.com/error.log;
root /var/example.com;
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
# CSS and Javascript -- this is the added location block
location ~* \.(css|js)$ {
expires 1y;
access_log off;
add_header Cache-Control "no-cache, public, must-revalidate, proxy-revalidate";
}
location = /movies {
return 301 $scheme://$host/movies/;
}
location ^~ /movies {
alias /var/example.com/movies/current/public;
fastcgi_index index.php;
try_files $uri $uri/ /movies/movies/index.php$is_args$args;
location ~* \.php {
fastcgi_pass unix:/run/php/php7.1-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(.*)$;
include /etc/nginx/fastcgi_params;
}
}
## many other location blocks like the immediate above snipped
# pass the PHP scripts to FastCGI server listening on /run/php/php7.1-fpm.sock
location ~ \.php$ {
try_files $uri /index.php =404;
fastcgi_pass unix:/run/php/php7.1-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
The
location ^~ /movies
block is a prefix location, and the^~
operator causes it to take precedence over regular expression locations. See this document for details.This is exactly the behaviour you need, because URIs that begin with
/movies
require a different document root to be set.To define special headers for URIs that begin with
/movies
and end with.css
or.js
, use another nested location block.For example: