High-Performance WordPress with W3 Total Cache and Nginx

March 14, 2011 at 3:26am.

This entry is about Programming

68 comments.

I recently set up a new server to host website for my clients. I took the opportunity to re-think how I have been serving sites and optimize the whole software stack for better performance. Rather than the usual LAMP (Linux/Apache/MySQL/PHP) stack, I decided to go with LEMP, switching Apache out for Nginx. Although most common PHP applications recommend Apache, they will actually run faster on Nginx. Usually all you just need to do is translate the .htaccess file rules into Nginx’s configuration file.

My first order of business once the new server was set up was to get WordPress running and to optimize its performance. The first few sites that would be going on the new hardware were using WordPress so although I will be going through a similar process for Expression Engine soon, WordPress was my test-case.

I always run the W3 Total Cache plugin with my WordPress installations. By storing copies of each rendered page to disk (as well as many other optimizations), W3TC dramatically decreases the load on the server under heavy traffic. This is particularly the case with the Nginx configuration I am about to show you, which lets most requests be handled by Nginx alone. Nginx was designed first and foremost as a reverse proxy, so it serves static files almost instantly and with minimal processor or memory usage. There are a number of sample configurations around the web for running WordPress with W3TC on Nginx, but none of them quite did it for me. For one thing, they all rely heavily on if statements, which are evil. So here is my take on it….

WordPress Settings

First, you need to install W3 Total Cache. This will add a “Performance” section at the bottom of the left-hand menu in your control panel. W3 Total Cache has many, many options and I am not going to explain them all here. To begin with, though, select the checkboxes to enable “Page Cache”, “Minify”, “Object Cache”, and “Database Cache”. The Page Cache method should be set to “Disk Enhanced” and all the others to “Disk” or “Opcode” if available.

Next, go to the “Page Cache” details page from the Performance menu and check off “Cache home page”, “Cache feeds”, and “Cache 404 pages”. The other two options in that section will be overridden by our Nginx configuration, so it doesn’t really matter what they are set to. Next, go to the “Minify” details page and add all the CSS and Javascript files that are used in your theme. This process is a bit fiddly—the upcoming version of W3TC will make it much easier—but the options are fairly self-explanatory. All the other settings should be fine with their defaults. The “Browser Cache” section, although very important for Apache setups, will also be overridden by what we are about to so, so you can ignore it.

Nginx Configuration

The important part of this post! You need to add the following configuration to your nginx.conf file (or to a separate file in /etc/nginx/sites-available/, which is the recommended way of doing things). I am assuming you already have Nginx running with PHP-FPM. If not, there are plenty of tutorials available around the web, depending on your Linux distro.

Caveats:

  • I had to comment out the PATH_INFO line in my fastcgi_params in order for images urls in minified CSS files to be correct. Doing so doesn’t seem to have had any negative effects.
  • Some of this code would be better off in your main http block, rather than the server block. I have arranged it this way for simplicity and clarity. Read more about how you should structure your configuration.
  • I’m not an Nginx configuration expert, so there may be ways to improve this code. Please share anything you see and I will update the post.

Comments:

Pulgafree gravatar

Pulgafree on March 20, 2011 at 6:00pm#1

I don’t get why didn’t you get any comments. Thank you so much for this “howto”. I implemented on all my WordPress client’s sites and I am more than happy seeing the results.

The Page Cache has made a BRUTAL improve on bandwidth and response times.

I have been using apache. But dropped in favor of nginx and PHP-FPM. Never looked back. WordPress sometimes hangs in loading. Some problem with the timing between PHP-FPM and MySQL. Haven’t figure it out yet. It happens randomly.

EliVZ gravatar

EliVZ on March 20, 2011 at 6:11pm#2

I’m glad it’s working well for you, Pulgafree! I haven’t seen that hanging issue with any of my sites yet, but if you figure out what’s causing it, will you leave another comment with the solution?

Pulgafree gravatar

Pulgafree on April 6, 2011 at 10:51pm#3

Hi. The problem was some misconfiguration on PHP-FPM, OpCode Cache and Mysql.

Used the atomic repo to update MySQL (I have CentOS 5.5), configured PHP this way and no more hangs:

PHP Version   5.2.17
Runtime Configuration:
Include Path
(include_path)  .:/usr/local/lib/php
Specifies a list of directories where the require(), include(), fopen(), file(), readfile() and file_get_contents() functions look for files.
Maximum Input Time
(max_input_time)  60 seconds
This sets the maximum time in seconds a script is allowed to parse input data, like POST, GET and file uploads.
Maximum Execution Time
(max_execution_time)  30 seconds
This sets the maximum time in seconds a script is allowed to run before it is terminated by the parser.
File Upload Settings:
Maximum File Size
(upload_max_filesize)  8 MB
The maximum size of an uploaded file.
Data handling:
Maximum Post Size
(post_max_size)  8 MB
Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload_max_filesize. If memory limit is enabled by your configure script, memory_limit also affects file uploading. Generally speaking, memory_limit should be larger than post_max_size.
Multibyte Function Overload
(mbstring.func_overload)  0
Overloads a set of single byte functions by the mbstring counterparts.

Pulgafree gravatar

Pulgafree on April 6, 2011 at 10:56pm#4

One question, I have this extension on php.ini:

extension=apc.so
apc.enabled = 1
apc.shm_segments = 1
apc.shm_size = 128M
apc.optimization = 0
apc.num_files_hint = 512
apc.user_entries_hint = 1024
apc.ttl = 300
apc.user_ttl = 300
apc.gc_ttl = 300
apc.cache_by_default = 1
apc.filters = “apc\.php$”
apc.slam_defense = 0
apc.use_request_time = 1
apc.mmap_file_mask = /tmp/apc-elefantina.XXXXXX
apc.file_update_protection = 2
apc.enable_cli = 0
apc.max_file_size = 2M
apc.stat = 0
apc.write_lock = 1
apc.report_autofilter = 0
apc.include_once_override = 0
apc.rfc1867 = 0
apc.rfc1867_prefix = “upload_”
apc.rfc1867_name = “APC_UPLOAD_PROGRESS”
apc.rfc1867_freq = 0
apc.localcache = 1
apc.localcache.size = 512
apc.coredump_unmap = 0
apc.stat_ctime = 0

For some reason, I can’t get it working right. It caches the configuration in w3 Total Cache. I mean, If I uncheck “Enable Minify”, and click on save, the next page loads and displays that Minify check is still on. I have to restart php-fpm to show the changes.

Should I reduce the apc ttl?

Ed gravatar

Ed on April 26, 2011 at 11:24pm#5

Hey Eli,

Great conf file!

I’ve been using it for the past few days in a new LEMP Test server and it’s working out great. So much more elegant than a lot of conf examples floating around.

Quick note - check this out - https://nealpoole.com/blog/2011/04/setting-up-php-fastcgi-and-nginx-dont-trust-the-tutorials-check-your-configuration/

There is a concern that config blocks which pass to php using location ~* \.php$ can be compromised. A number of approaches to locking this down are mentioned in that post but the method I’ve used is to add

try_files $uri =404;

as the first line inside that config block.

Ed

EliVZ gravatar

EliVZ on April 26, 2011 at 11:39pm#6

Ed,

I may be wrong, but I believe that my try_files $uri /index.php; already solves this problem. If the file does not exist on the server, Nginx will pass the request off to WordPress, which then throws a 404.

(I actually have cgi.fix_pathinfo=0 in my php.ini also, which I should have mentioned in the post.)

Ed gravatar

Ed on April 27, 2011 at 7:18pm#7

Hey Eli,

I think you’re right - I re-read that post again.

You should submit your conf for inclusion to the nginx “Full Examples” webpage on the nginx website - http://wiki.nginx.org/Configuration

I think you’re conf is the best I’ve found so far - did you write it yourself?

Really top work!

EliVZ gravatar

EliVZ on April 27, 2011 at 8:29pm#8

That’s a good idea, and I will look into it. I definitely used ideas from many of the WP configurations I found around the web, but I also re-wrote most everything to conform to Nginx best-practices.

Thanks for your comments!

okone gravatar

okone on April 28, 2011 at 1:30pm#9

This is a great post EliVZ, but I do have one problem to report, although its likely a fault with nginx rather than your configuration.

If you perform a search on wordpress and try to navigate to page two of the results, it actually directs you to page two of the blog. I have tried this on the few places I know to have the try_files rules in place and it seems to happen on all of them.

Of course, it might just be me going crazy but if anyone has any idea how to fix it let me know. I may end up asking in the nginx forums and see if they have any ideas.

Besides that, this is a really great post, so thank you!

EliVZ gravatar

EliVZ on April 29, 2011 at 4:28am#10

Okone-

Hmm, good catch. It’s doing that on my sites too, although it happens even with caching turned off completely. I’m thinking there must be some incompatibility between Nginx and WordPress’s permalink handling. I just haven’t been able to track it down yet….

I will report back if I can figure out a fix, or if anyone else has seen this issue, please chime it.

okone gravatar

okone on April 29, 2011 at 1:33pm#11

EliVZ

I created a thread on the nginx forums and we have an answer.

If you use:

try_files $uri $uri/ /index.php?q=$uri&$args;

instead of the recommended

try_files $uri $uri/ /index.php;

then search works fine. It is indeed a problem with wordpress internal rewriting.

EliVZ gravatar

EliVZ on April 29, 2011 at 5:33pm#12

Okone, you rock! I’ve updated my code and search works perfectly now. Thanks for figuring that out.

Robert Kingston gravatar

Robert Kingston on May 29, 2011 at 10:35am#13

Eli, YOU rock.

W3TC should have this conf inside its “Install” page.

Mads Madsen gravatar

Mads Madsen on June 5, 2011 at 2:24am#14

I found a small problem with your config, the css and js files where not served as static content, it was still being served by PHP.
So changing:

rewrite ^/wp-content/w3tc/min/(.+\.(css|js))$ /wp-content/w3tc/min/index.php?file=$1 last;

to

location ~ \.(css|js)$ {
  if (-f $request_filename) {
  break;
  }
  rewrite ^/wp-content/w3tc/min/(.+\.(css|js))$ /wp-content/w3tc/min/index.php?file=$1 last;
}

Fixes it! :-)

Thank you for the nginx rules!

EliVZ gravatar

EliVZ on June 6, 2011 at 12:46am#15

Mads-

Damn, you’re totally right. I’ve updated the configuration file. Thanks for catching that!

sanjeev gravatar

sanjeev on July 17, 2011 at 6:05pm#16

i request to all the website owners have this plugin..this plugin work great…

Sam gravatar

Sam on August 29, 2011 at 8:40am#17

Hello, how can I know nginx is actually using w3’s disk cache, cause I can’t see nginx accessing it through the access logs…

EliVZ gravatar

EliVZ on August 29, 2011 at 4:20pm#18

Sam-

I’m sure there is a slicker way of checking where pages are being served from, but my quick-check is to edit the cached HTML file (in /wp-content/
w3tc/pgcache) with an extra comment at the bottom or whatever. Then check your website and see if the modification came through. Once you see that you are being served the cached copy, you can just click “Clear Page Cache” in W3TC to get a pure copy again.

Sam gravatar

Sam on August 29, 2011 at 7:45pm#19

Ah nice, thank you for pointing that out EliVZ!

SLT-A77 gravatar

SLT-A77 on November 17, 2011 at 11:42pm#20

hey there and thank you to your info – I have definitely picked up anything new from right here. I did on the other hand experience several technical points the use of this website, since I experienced to reload the site many instances previous to I could get it to load correctly. I were thinking about if your web host is OK?

NikolasTesla gravatar

NikolasTesla on January 14, 2012 at 7:04pm#21

I found the answer in <a >google</a>, remove the topic pls.

Erick gravatar

Erick on January 15, 2012 at 5:55am#22

The “If” conditions in nginx setup are the best way to screw up nginx performance and get is close to apache. Remove the IFs and you’ll be benefitting, otherwise you might as well keep it simple and stick with apache.

Yoav Aner gravatar

Yoav Aner on March 19, 2012 at 8:46am#23

Thanks for this guide. It got me started on configuring nginx with wordpress, which seems like a bit of a dark art. One thing I noticed however, perhaps it’s only in recent additions to W3TC, but W3TC generates its own nginx.conf file, which can/should be included within the master config? I’ve written a post with instructions on how to configure this on webfaction and benchmark between Apache, Nginx + PHP-FPM and Varnish.

EliVZ gravatar

EliVZ on March 19, 2012 at 3:41pm#24

Yoav,

Yes, Frederick added the config file generation around the same time that I posted this script. I still prefer my own approach, which is much “lighter” and better follows Nginx best-practices, however they accomplish much the same result. I should probably update the post to explain the situation though….

Yoav Aner gravatar

Yoav Aner on March 20, 2012 at 11:14am#25

Thanks Eli,

Yes, I had a look at the auto-generated rules, and I can imagine they can be optimized (at least judging by the note about avoiding if statements). W3TC also adds its own optimization headers, which might or might not be desirable.

For people who are less comfortable with complex nginx rules, using the auto-generated rules is probably a good option.

p.s. I also noticed there are a couple of typos on your gist, for example there are two semicolons on one line, and if memory serves me nginx complains about a couple of other small things… it will be really useful if you post the most up-to-date version if you can.

Cheers
Yoav

Faridha Dwi H gravatar

Faridha Dwi H on June 21, 2012 at 10:53am#26

What causes a 502 Bad Gateway ?
Sometime i got bad gateway message

EliVZ gravatar

EliVZ on June 21, 2012 at 3:15pm#27

Faridha,

502 errors can be caused by any number of things, and they’re hard to debug. Generally, it’s a server configuration issue, but I can’t really say what without knowing how your server is set up. Does it go away when you turn off W3TC? If so, I would try disabling one part of W3TC at a time (page caching, object caching, etc.) and see if you can narrow down where the issue is.

Dubai call girls gravatar

Dubai call girls on June 26, 2012 at 9:49am#28

بالتأكيد لديك بعض الآراء ووجهات النظر مقبولة. elivz.com يقدم نظرة جديدة على هذا الموضوع.

Regeapave gravatar

Regeapave on June 26, 2012 at 1:29pm#29

<a ><img>http://s012.radikal.ru/i320/1112/5b/5919d02f5246.jpg</img>
<img>http://s47.radikal.ru/i118/1112/cd/2e0462ac92b8.jpg</img></a>
Tegs: декоративная штукатурка клавелл  декоративная штукатурка ремонт  декоративная штукатурка деко флекс.
<u>декоративная штукатурка кристалл </u>
как нанести декоративную штукатурку
декоративная штукатурка mediterraneo
<a ></a>

Artesanos gravatar

Artesanos on September 20, 2012 at 1:21am#30

’m sure there is a slicker way of checking where pages are being served from, but my quick-check is to edit the cached HTML file

Danny gravatar

Danny on September 23, 2012 at 2:56pm#31

Hope someone’s still watching this post

Running Wordpress 3.4.2 & W3TC 0.9.2.4, seeing the following errors at the top of the W3TC page -

It appears Page Cache URL rewriting is not working. If using apache, verify that the server configuration allows .htaccess or if using nginx verify all configuration files are included in the configuration

It appears Minify URL rewriting is not working. If using apache, verify that the server configuration allows .htaccess or if using nginx verify all configuration files are included in the configuration

Hope it’s nothing serious!!

EliVZ gravatar

EliVZ on September 23, 2012 at 6:05pm#32

Danny- You will just need to “ignore” those messages. W3TC can’t verify the configuration with Nginx like it can with Apache. It doesn’t mean it is not working, just that W3TC is unable to tell.

Danny gravatar

Danny on September 24, 2012 at 11:49am#33

Thanks EliVZ, hard for me to ignore errors, but I’ll try :)

Etefetism gravatar

Etefetism on October 2, 2012 at 4:10am#35

<a >sharp pain in middle finger joint </a>
collectively other half.  Risks affiliated with sexually transmitted diseases like the usage of herbal remedies, minerals and vitamins each day given that fears right from unsatisfied people are swiftly while tips over that will upset time paid out by these distinct services.  Bacterial Vaginosis Warning signs This genital odor. They’ve been regular within vaginal area. A different typical common anti-biotic specified by mouth or simply put on the actual vaginal area stomach acid. Throughout this problem is usually to   <a >finger joint pain from typing </a> practicing shapes and sizes and variations comprise bouquets, vodafone flowers, vanilla flavour and additionally add-ons and also offers who are seeking lactic acidity unhealthy bacteria, you likewise contribute to fibroid constitution.  Keep in mind, these have utilizing to 2 quarts water. Pick out a comprehensive conversing with fantastic incidence.  If consider using   <a >pain in middle finger joint </a>
<a >finger joint pain bump </a>

Self Sabotage gravatar

Self Sabotage on October 23, 2012 at 4:21pm#36

I’ve also used the configuration file. Thanks for that! Saboteur WithinI should probably update the post to explain the situation though…

Michael McNamara gravatar

Michael McNamara on November 15, 2012 at 3:42am#37

@Danny - you don’t need to ignore the errors, just turn off the ‘Verify rewrite rules’ option under the Miscellaneous settings (down toward the bottom of the page).

@EliVZ thanks for sharing your configuration!

Cheers!

EliVZ gravatar

EliVZ on November 15, 2012 at 5:52am#38

Good call, Michael. I never noticed that checkbox, I just always re-ignore the messages after each plugin update.

Debt consolidation advice gravatar

Debt consolidation advice on December 1, 2012 at 1:40am#39

usfwxfmjw{, Debt consolidation secured loan uk, unqIHbU, Uk personal debt consolidation unsecured loan, LmQNEoX, http://debtconsolidationtutorial.com/ Debt Consolidation, tBmNYMh.

Palaniappan gravatar

Palaniappan on December 26, 2012 at 9:18am#40

I want to host my site into VPS or Dedicated server and i am newbie to VPS & dedicated servers. I have very basic knowledge of Linux commands.

I am looking for best free LAMP stack. I found couple of scripts, but i very much interested on http://centminmod.com (Menu based Nginx, PHP-FPM, MariaDB auto installer script for CentOS). Is this secured enough? Are there any known issues? This will help me to proceed further.

EliVZ gravatar

EliVZ on December 26, 2012 at 7:33pm#41

I am not familiar with the script you mentioned (although it looks promising). I am currently using UNIXy to host many of my sites, they offer a fully-managed VPS, which they will configure to run Nginx & PHP-FPM. They handle the server maintenance and security, which is nice if you are not super-familiar with that stuff (or just don’t have time for it).

Elileamnegeva gravatar

Elileamnegeva on April 1, 2013 at 11:51pm#42

Making friendship <a >Cheap Pandora Bracelet Beads</a>
is not very complex. Should you not know from which to start then search for a reputed bookshop, which deals in best books. Let him express about the booklets that supply information about making own bracelets. These booklets contain numerous ideas and countless instructions in making <a >Cheap Pandora Bead Bracelets</a>
. The most easy form of <a >Pandora Bead Bracelets Shop</a>
have looping and cording of rope with beads. When you are finished you can attach the both ends.

sapOppobe gravatar

sapOppobe on April 12, 2013 at 4:24pm#43

My husband and i have been quite ecstatic when Chris managed to round up his investigation through the entire ideas he made using your site. It’s not at all simplistic to just be giving freely tricks that people might have been making money from. And we all recognize we’ve got you to give thanks to because of that. The explanations you have made, the simple web site navigation, the friendships you will help create - it is everything incredible, and it’s facilitating our son in addition to our family consider that the idea is brilliant, and that is extraordinarily serious. Many thanks for all! 
| Selecting Rapid Tactics For Juicer Reviews

Gwyneth Llewelyn gravatar

Gwyneth Llewelyn on April 17, 2013 at 4:54pm#44

Hi Eli,

Awesome tutorial, thanks very much for posting it!

I’m so used to Apache that for over a decade I haven’t used anything else. I was always afraid of Nginx because of the lack of direct .htaccess support, and since WP relies so heavily on that (as well as its plugins, namely, W3TC), I was always very hesitant about “switching” to Nginx.

Recently one of my blogs went down due to the insane WP botnet attacks. So I temporarily pushed it elsewhere to fix the issues. But I could only afford a tiny VM with 512 MB. After spending countless hours in tweaking Apache + PHP FastCGI to get as much performance as I could squeeze out of it, and reading many performance tweaking tutorials, it was clear that all those people saying “dump Apache, use Nginx” couldn’t be all wrong. So, well, I tried that for a change.

Switching over to Nginx wasn’t so hard as I thought, even though I didn’t get it right the first time. Still, even with W3TC not fully operational, the improvements were notorious. Then I saw your tutorial and thought I’d add W3TC support on top of it.

Needless to say, as countless others have experienced, Nginx performs admirably better in all regards, and your configuration certainly works — I can see the embedded comments from W3TC on the served pages. The underpowered server never hits the swap, and is able to serve some ten concurrent connections simultaneously without dropping a byte — while under Apache it thrashed completely and pretty much became totally unusable, even with just a few connections. Being an utter Nginx newbie, I haven’t yet tweaked its settings to get a bit more performance (and I understand that the major tweaks will very likely be under PHP-PFM). But I did some benchmarking with ‘ab’, and the results are impressive: Nginx shows almost 10x times the performance, although, of course, ‘ab’ is not a perfect benchmarking tool (it just hits the same page over and over again).

Gwyneth Llewelyn gravatar

Gwyneth Llewelyn on April 17, 2013 at 4:55pm#45

Under Ubuntu 10.4, with a very optimized Apache 2.2 + PHP FastCGI + APC:


Server Software:      Apache
Server Hostname:      [edited out]
Server Port:        80

Document Path:      /
Document Length:      82562 bytes

Concurrency Level:    10
Time taken for tests:  387.585 seconds
Complete requests:    10
Failed requests:      0
Write errors:        0
Total transferred:    534598 bytes
HTML transferred:    532764 bytes
Requests per second:  0.03 [#/sec] (mean)
Time per request:    387585.221 [ms] (mean)
Time per request:    38758.522 [ms] (mean, across all concurrent requests)
Transfer rate:      1.35 [Kbytes/sec] received

Connection Times (ms)
          min mean[+/-sd] median   max
Connect:    69 12992 8682.8 16550   27905
Processing: 30000 97943 143236.5 30000 369716
Waiting:      0 58304 122915.5     0 291520
Total:    35841 110935 136531.8 46667 369785

Percentage of the requests served within a certain time (ms)
  50%  46667
  66%  47340
  75%  57906
  80%  369785
  90%  369785
  95%  369785
  98%  369785
  99%  369785
100%  369785 (longest request)
</pre>

Note that I gave up after just 10 requests.

Gwyneth Llewelyn gravatar

Gwyneth Llewelyn on April 17, 2013 at 4:55pm#46

Now with Nginx + PHP-PFM (using Unix sockets and not network connections, max_children = 5, start_servers = 2):


Server Software:      nginx/1.1.19
Server Hostname:      [edited out]
Server Port:        80

Document Path:      /
Document Length:      87715 bytes

Concurrency Level:    10
Time taken for tests:  387.047 seconds
Complete requests:    180
Failed requests:      146
  (Connect: 0, Receive: 0, Length: 146, Exceptions: 0)
Write errors:        0
Total transferred:    15840863 bytes
HTML transferred:    15788483 bytes
Requests per second:  0.47 [#/sec] (mean)
Time per request:    21502.607 [ms] (mean)
Time per request:    2150.261 [ms] (mean, across all concurrent requests)
Transfer rate:      39.97 [Kbytes/sec] received

Connection Times (ms)
          min mean[+/-sd] median   max
Connect:    57 12220 9146.4 15179   29378
Processing:    0 8595 10036.3   2893   32871
Waiting:      0 8077 9316.8   2549   32507
Total:    7712 20815 4658.1 20955   33891

Percentage of the requests served within a certain time (ms)
  50%  20955
  66%  22124
  75%  23144
  80%  24445
  90%  26411
  95%  28576
  98%  32450
  99%  32451
100%  33891 (longest request)
</pre>

You can see the huge difference!

I still will need to address the high level of “failed” requests. Apache doesn’t fail any requests, but, in contrast, it just served 10 complete requests over the same period… Nginx served 180!

Gwyneth Llewelyn gravatar

Gwyneth Llewelyn on April 17, 2013 at 6:44pm#47

Oh… it seems that W3TC is now fully Nginx-aware! It auto-detects Nginx and drops a nginx.conf file on the WP root. Very clean too, not a single ‘if’ in sight. LOL!

This should be enough for W3TC:

server {
  listen     80;
  reset_timedout_connection on;

  server_name [your site name];
  root /var/www/[your site name];
  index index.php index.html index.htm;
  client_max_body_size 500m;
  autoindex on;
  access_log /var/log/nginx/[your site name]-access.log;
  error_log /var/log/nginx/[your site name]-error.log;

  include /var/www/[your site name]/nginx.conf;

  location / {
      index index.php index.html index.htm;
      try_files $uri $uri/ /index.php?$args;
  }

  # Cache static files for as long as possible
  location ~* \.(xml|ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|css|rss|atom|js|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|b
      try_files     $uri =404;
      expires       max;
      access_log     off;
  }

  # Deny access to hidden files
  location ~* /\. {
      deny         all;
      access_log     off;
      log_not_found   off;
  }

  # Pass PHP scripts on to PHP-FPM
  location ~* \.php$ {
      try_files     $uri /index.php?$args;
      fastcgi_index   index.php;
#      fastcgi_pass   unix:/var/run/php5-fpm.sock; # faster, no networking
      fastcgi_pass   127.0.0.1:9000;
      include       fastcgi_params;
  }

}

Gwyneth Llewelyn gravatar

Gwyneth Llewelyn on April 18, 2013 at 5:07am#48

When adding keepalive, and putting CloudFlare as a proxy/CDN in front of everything, the benchmarking shows even better interesting results:


Finished 219 requests


Server Software:      cloudflare-nginx
Server Hostname:      [edited out]
Server Port:        80

Document Path:      /
Document Length:      80979 bytes

Concurrency Level:    10
Time taken for tests:  500.001 seconds
Complete requests:    219
Failed requests:      163
  (Connect: 0, Receive: 0, Length: 163, Exceptions: 0)
Write errors:        0
Non-2xx responses:    29
Total transferred:    15516153 bytes
HTML transferred:    15419896 bytes
Requests per second:  0.44 [#/sec] (mean)
Time per request:    22831.083 [ms] (mean)
Time per request:    2283.108 [ms] (mean, across all concurrent requests)
Transfer rate:      30.30 [Kbytes/sec] received

Connection Times (ms)
          min mean[+/-sd] median   max
Connect:    48 20649 16768.5 15360   63818
Processing:    0 1447 7097.7   132   60668
Waiting:      0 1308 7072.9     0   60668
Total:    5354 22096 16626.9 16197   63959

Percentage of the requests served within a certain time (ms)
  50%  16159
  66%  18994
  75%  21708
  80%  23258
  90%  60659
  95%  61549
  98%  62179
  99%  62665
100%  63959 (longest request)
</pre>
It’s a slight edge which should be much more useful in “real” environments than on benchmarking!

EliVZ gravatar

EliVZ on April 18, 2013 at 6:37pm#49

Wow, Gwyneth! That’s some great data to have… thanks for sharing it.

Gwyneth Llewelyn gravatar

Gwyneth Llewelyn on May 11, 2013 at 7:21pm#50

Well, thanks for your inspiration! It prompted me to write my own tutorial. Nginx has evolved a little bit since your own post, so I thought I could do a little more research and expand a bit, namely, getting rid of the many ifs on your suggested configuration.

Marco gravatar

Marco on June 5, 2013 at 7:33am#51

Nice tut!

online shop china gravatar

online shop china on July 22, 2013 at 9:33am#52

Hello friends, how is the whole thing, and what you wish for to say concerning this post, in my view its truly amazing in favor of me.

HedUniorieCen gravatar

HedUniorieCen on July 23, 2013 at 10:05pm#53

Jestes mlodym kierowca – nie przerwales wciaz <a >tanie polisy oc ac</a>  natomiast skladki w srodku OC rokrocznie Cie rozpuszczaja? Zapraszamy <a >mlody kierowca tanie oc</a> stronice oddanym strategiom na zaoszczedzenie na polisie, jakie z powodzeniem aplikowac zdolaja najmlodsi zmotoryzowani. Dowiesz sie w owa strone, czy strategia na koligata istnieje w rzeczy samej wlasnie zasadna, kiedy ja maluja i w jakim celu trzeba dubel ciegi pomyslec, nim okupi sie polise w firmie radzonej przy uzyciu familie plus familiarnych. Jesliby wygrywasz na chleb zbytnio kolkiem, to sposrod pewnoscia zaciekawia Cie wyprobowane sposoby, jakie przyzwola Ci zmniejszyc danine za oslona komunikacyjne. Kierowcow w wszelkim wieku sposrod kolejek inwitujemy az do przeczytania, oznacza to nalezaloby pokladac nadzieje rankingom OC a opiniom o ubezpieczeniach

HedUniorieCen gravatar

HedUniorieCen on July 24, 2013 at 6:36pm#54

Jestes mlodym kierowca – nie przerwales jeszcze <a >ubezpieczenie oc</a>  rowniez sciep wewnatrz OC rokrocznie Cie frygaja? Zapraszamy <a >mlody kierowca tanie oc</a> stronice oddanym metodom na zaoszczedzenie na polisie, jakie z powodzeniem wykorzystywac zdolaja najmlodsi zmotoryzowani. Dowiesz sie w tamtym miejscu, azaliz postepowanie na koligata istnieje tak tak bardzo korzystna, gdy ja maluja tudziez po co wypada dwie plagi pomyslec, przedtem wykupi sie polise w jednostce doradzanej dzieki rodzine a znajomych. Jesli wygrywasz na bochenek zbyt kolkiem, owo z pewnoscia zaintryguja Cie wyprobowane sposoby, jakie uznaja Ci zredukowac wyplate zbyt asekurowanie komunikacyjne. Kierowcow w kazdym wieku sposrod kolumn inwitujemy az do przeczytania, azaliz nalezaloby pokladac nadzieje rankingom OC plus opiniom o ubezpieczeniach

sac longchamp gravatar

sac longchamp on August 21, 2013 at 6:03am#55

this is the dumbest fucking video ever. “every thing is suck a good fit, its just beautiful” just goet a room i mean really? fuck this

2012 sac longchamp trousse de toilette graphite pa gravatar

2012 sac longchamp trousse de toilette graphite pa on August 23, 2013 at 5:47am#56

i appreciate you. you posted very informative material in this article.

Poorgenog gravatar

Poorgenog on October 14, 2013 at 3:47pm#57

“This event will return for 2013 and the response from the runners was that it was an amazing run with beautiful scenery, great trail, well organized with awesome food and prizes,” said Hiom.“Nautica is passionate about preserving the world’s oceans and we are happy to be working with Oceana to reach consumers with important messages about how to get involved with this important cause,” said Karen Murray, President of Nautica. <a >north face cyber monday</a> C’est ainsi que je me suis d’abord fait connatre et cela m’a permis de dterminer mes horaires.Inventories are coming down (4% in Q1, should be 10% for the year) but it will take some time to get to manageable levels.  I recently spent several days on Yakushima, an island with 40% of its land area designated as a World Heritage Site and which for this reason is a Mecca for hiking and backpacking in Japan.The North Face HyVent hiker hat is a rainy day essential for folks who love being outdoors no matter what the weather is like.

AbelJOVofcwbmq gravatar

AbelJOVofcwbmq on October 17, 2013 at 12:37pm#58

Psychological disorders such as depression, fear, anxiety or guilt can cause sexual problems like erectile dysfunction. At one time, psychological factors were thought to be the major cause of erectile dysfunction. Currently, the physicians know that physiological factors are present in the most men who suffer from erectile dysfunction. Embarrassment or performance anxiety can make a physical problem worse. Many medicines cause problems with sexual function like erectile dysfunction including drugs prescribed for high blood pressure, depression, heart disease and prostate cancer.

inertiets gravatar

inertiets on October 17, 2013 at 3:23pm#59

Parents upload the photo to the Take Your Parents to Lunch Day microsite and fill out the official entry formAccording to police, a Hispanic male entered the bank waiving what appeared to be a black and silver handgun and announced the robbery. <a >discount north face jackets for kids</a> Click “Reply” at the bottom of the comment; after being approved your comment will appear directly underneath the comment you replied to.They have a greatMore assortment of Briggs Riley luggage in all sizes, travel accessories and clothes (Horny Toad, North Face, Patagonia and Ugg). <a >north face jackets on sale womens</a> The suspect, described as an Asian man between five feet, 10 inches and six feet, two inches tall, was seen wearing a black fedora, black leather jacket, Ray Ban sunglasses, a North Face backpack and black and white shoes.Our own north face outlet retailer not merely can provide an individual the particular North Face Smooth Covering Jacket, but in addition you <a >north face denali jackets for women</a> The gun was significant because it’s the only time I remember my dad having obviously been involved in the selection of a gift.

HernesarseMak gravatar

HernesarseMak on October 18, 2013 at 5:28pm#60

Let’s be honest; the moment the physical exercise will begin, we’re therefore occupied keeping way up that working out create is definitely the one thing to generally be destroyed.It’s fortunate for Leicester that Minette is with him, since the “control panel” to the device is flowing with El, some of it quite hostile. <a >uggs salg</a> When my girlfriend and I get in the car, I tell her that if she wants to go on with them I can get a cab home and she can take my car or that we can drive home then she can take the car back out again.how many do you think are playing now and would take the chance to come out? not a one. <a >uggs for men</a> Mr Purcell told the court he and Ms Liston had been carrying on an affair for several years.Moncler estticas ms pequeos, la ropa es la mercanca que tienen dio a conocer despus de chaquetas de las seoras Moncler chaquetas as como las chaquetas de los Moncler hombres.

toms canada gravatar

toms canada on October 27, 2013 at 10:52pm#61

The boiled soda water is also responsible in compensation responsibility every heyday, uninfected, attach?case
toms canada http://www.railway.gov.bd/images/buy.asp

Discount Fendi HandbagsAll Cheap 1:1 Replica gravatar

Discount Fendi HandbagsAll Cheap 1:1 Replica on November 9, 2013 at 1:56am#62

I visited many——websites——however——the audio feature——for audio songs existing——at this website——is in fact——superb——prada bags outlet,http:/dina-sallam.com/louis-vuitton-outlet.html

kazino80 gravatar

kazino80 on November 28, 2013 at 2:55am#63

стратегия покера онлайн <a >игровые автоматы пополнение счета смс qiwi</a> интернет казино чемпион лига англии, как играть в покер на деньги онлайн с выводом денег <a >мобильный онлайн покер на деньги</a> интернет игровые автоматы казино <a >играть в игровые автоматы джекпот онлайн на деньги отзывы форум</a> игровые автоматы играть бесплатно онлайн free <a >играть покер онлайн на реальные деньги на русском языке</a>

Edward gravatar

Edward on April 5, 2014 at 12:29pm#64

Your post was one of the first I found when wanting to speed up my blog.  Helped me decide to switch over to nginx from apache.  Thanks!

Unfortunately, I’m still getting occasional strange errors - “upstream did this or that bad thing” - so I’m still learning how to config nginx + php-fpm…

iPhone5sケース人気 gravatar

iPhone5sケース人気 on May 9, 2014 at 11:22pm#65

次はちょうど個人に合わせたiPhoneカバーに関する顧客からの要望に属するこの上昇世界的な認識を導く重要な理由についてです。 あなたがiPhoneを得るためにあなたの群れ、その後修正されたhoesjesよりも、より高度な差別化したい場合には優れた代替手段です。 アイテムは、近代的なブラウズのもの自身の携帯電話に加えて、余分な上品含まれています。この特定は、おそらくカスタムiPhoneカバーに関連する欲求に人気の進行レベルを駆動する主要な原因である。 あなたがたく、この束iPhoneを対象とし、その後個別hoesjesは素晴らしい選択であると同じではないに注意すべきである。 これは、はるかにトレンディでさえシックなチェックアウト、個人のスマートiPhoneを与えます。

Gerainark gravatar

Gerainark on June 26, 2014 at 8:21am#66

They are among 25 selections the library is inducting Wednesday into the National Film Registry. <a >tiffany s canada</a> Painting mostly in the early to mid1800s, Ferneley specialized in painting jockeys and their rides.Thus, Metcalf changed tactics by inventing a robotic tank, which he secretly designed so that Hardware could easily defeat it. <a >tiffany canada</a> NEW YORK (AP)  Shares of luxury retailers rose Tuesday as upscale jewelry company Tiffany Co.

Gerainark gravatar

Gerainark on June 26, 2014 at 8:22am#67

Speaking of taller I would eat disgusting “growth balls” that tasted like nasty butter.The Tiffany lamp’s not an antique, though the table is. <a >tiffany & co uk</a> Said Friday that its secondquarter profit fell but beat analyst expectations as its steep sales declines moderated, providing a sparkle of hope amid the moribund luxury market.Revenue at stores opened at least a year in the Americas was unchanged in the quarter and was in line with expectations. <a >tiffany and co uk</a> The only reason she doesn’t get turned in is because she spends all her time with lowlifes like her who dont care.Great for taking notes, trading information, and keeping yourself busy while keeping your brain active.

Oakleyslcvav gravatar

Oakleyslcvav on July 10, 2014 at 2:47am#68

NORWALK, Conn. A 19 year old woman was arrested by Norwalk police Wednesday in the theft of $8,700 worth of mostly consumer electronic items in a November burglary at a home on Allen Road.If arrogance was contagious they all be sneezing. All Aryan, all dudely, and now all that stands between those thousands of State Department personnel and Iraq. Oh yes: the seersuckered and bow tied diplomats are supposed to supervise the mercs and keep them on the right diplomatic path, kind of like expecting the chess club to run herd on the football team.锘縒hat’s in store <a >foakleys for sale</a> She predicts it will also be a few years before Burberry, Victoria’s Secret or J. Crew try to enter the Ottawa market   but they will.Meanwhile, decor stores Crate Barrel and Pottery Barn and cookware emporium Williams Sonoma are looking at the capital.
clasesUniversidad UACAEl BaguaFeng Shui para el 2014Colegio de Arquitectosand IF you really learn all that the course offers <a >cheap replica Oakleys for sale</a>cheap What’s the Use of Celebrity Sunglasses?
Edit 2 : I went in and made a formal report at the sheriff department. The guy taking the report seemed initially excited at there being a left behind cell phone, but turned into a bit of a douche when he heard there was minimal damage done to my car. After that he seemed to lose interest in the whole situation and turned into a bit of douche. <a >fake oakley sunglasses usa</a> Apple Computer Inc.‘s iconic iPod has proved that technology isn’t enough   the product also has to look stylish.

Got something to say?