0

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?

2 Answers 2

5
+50

You can use if in server block it is perfectly safe. Working example with relevant lines:

server {
    listen   80;
...skip...
    if ($uri ~* "/forum" ) {set $no_cache 1;}
...skip...

    location ~ \.php$ {

        fastcgi_cache_bypass $no_cache;
        fastcgi_no_cache $no_cache;

      ...other fastcgi-php content...
}
1

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:

location ~ ^/forum/.*\.php$ {
    // forum php setup here
}
location ~ \.php$ {
    // regular php setup here
}

It's not entirely DRY but it's straightforward and easy to read when you come back to it in 6 months.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .