Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I'm looking to reduce the load on my server.

I already have my php files setup so whenever someone first visits a particular page, it caches the html output to a whatever.htm file in my /cache folder.

I'm using nginx as a 'frontend' to my apache server (which only serves php files).

Is it possible to setup nginx so that :

1) If a request for index.php is requested, first check to see if index.htm exists in the /cache folder - if so, serve that page instead. If not, pass off the request to apache.

2) I would only like nginx to check the cache folder only for a particular set of filenames (not all php files) - can an array or something similar be setup that way? (only check cache for index.php, contact.php, faq.php, etc requests)

3) If serving a .htm "cache" file, it is possible to to make it look like it's still serving the .php file? I just don't want the extension to show .htm in the address bar and start having duplicate content issues with the search engines.

Any help would be appreciated!

share|improve this question

1 Answer 1

Well, since your application controls your cache files itself, you can make use of try_files directive:

location ~ \.php$ {
  try_files /cache/$uri.html @php;

  # the directives below will affect cache serving
}

location @php {
  # pass to FastCGI or Apache proxy for PHP rendering
}

For a request to whatever.php this will check if cache/whatever.php.html exists and return it if it does. Otherwise, the request goes to PHP.

Alternative. Frankly speaking, this method will work, but it's rather verbose and is going to be much more verbose if you'd decide to bypass the cache for some requests. For example, what if you'd like to go directly to PHP if there is a debug argument: whatever.php?debug ?

Nginx has a good answer to this problem, its built-in caching. Assuming you are using FastCGI to serve PHP, the Nginx configuration would look like this:

# you have to declare a cache at "http" level
http {
  fastcgi_cache_path   /path/to/cache  levels=1:2
                       keys_zone=my_cache_id:10m
                       inactive=5m;
}

# server level
location / {
  fastcgi_cache my_cache_id;

  # cache HTTP replies with statuses 200, 302 for 5 minutes:
  fastcgi_cache_valid 200 302 5m;

  # do not cache if there is a "debug" argument or PHP returned HTTP header Pragma:
  fastcgi_no_cache $arg_debug$http_pragma;

  # other FastCGI directives...
  fastcgi_pass localhost:9000;
}

Nginx documentation is here

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.