I have just set up a new server with nginx (which I am new to) and PHP. On my site there are essentially 3 different types of files:
- static content like CSS, JS, and some images (most images are on an external CDN)
- main PHP/MySQL database-driven website which essentially acts like a static site
- dynamic PHP/MySQL forum
It is my understanding from this question and this page that the static files need no special treatment and will be served as fast as possible.
I followed the answer from the above question to set up caching for PHP files and now I have a config like this:
location ~ \.php$ {
try_files $uri =404;
fastcgi_cache one;
fastcgi_cache_key $scheme$host$request_uri;
fastcgi_cache_valid 200 302 304 30m;
fastcgi_cache_valid 301 1h;
include /etc/nginx/fastcgi_params;
fastcgi_pass unix:/var/run/php-fastcgi/php-fastcgi.socket;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /srv/www/example$fastcgi_script_name;
fastcgi_param HTTPS off;
}
However, now I want to prevent caching on the forum (either for everyone or only for logged-in users - haven't checked if the latter is feasible with the forum software). I've heard that "if is evil" inside location blocks, so I am unsure how to proceed. With the if inside the location block I would probably add this in the middle:
if ($request_uri ~* "^/forum/") {
fastcgi_cache_bypass 1;
}
# or possible this, if I'm able to cache pages for anonymous visitors
if ($request_uri ~* "^/forum/" && $http_cookie ~* "loggedincookie") {
fastcgi_cache_bypass 1;
}
Will that work fine, or is there a better way to achieve this?
You can use if in server block it is perfectly safe. Working example with relevant lines:
Another way to go about this is a separate location block above your default location block to catch and act differently on things destined for the forum:
It's not entirely DRY but it's straightforward and easy to read when you come back to it in 6 months.