Showing posts with label nginx. Show all posts
Showing posts with label nginx. Show all posts

tuning nginx compression and decompression

Much of what NGINX has configured for us by default is great, but there are some settings that we can adjust to make the server perform even better. One of the adjustments that we can make is to have NGINX compress resources before sending them to the client. This modification isn’t free, as it does add some CPU overhead, but not enough to outweigh the benefits.
Note: the commands in this video are run as the root user.

Documentation For This Video

Configuring and Enabling GZIP

We came across gzip when we first installed NGINX and looked at the default configuration, but it was commented out. The simplest way to enable compression for our responses is to uncomment that line in our nginx.conf file:
/etc/nginx/nginx.conf (partial)
    gzip on;
That change is simple enough, but there’s more that we can do to make this better by using some of the other directives from the gzip module. By default, we’re not going to compress the responses that we’re getting from proxied servers or any piece of content that isn’t HTML. Let’s make some modifications to compress more of what we know we’ll respond with:
/etc/nginx/nginx.conf (partial)
  gzip on;
  gzip_disable msie6;
  gzip_proxied no-cache no-store private expired auth;
  gzip_types text/plain text/css application/x-javascript application/javascript text/xml application/xml application/xml+rss text/javascript image/x-icon image/bmp image/svg+xml;
  gzip_min_length 1024;
  gzip_vary on;
Let’s break down these directives:
  • gzip_disable - Ensure that we’re not sending compressed responses to older versions of Internet Explorer (hopefully no one is actually using these browsers)
  • gzip_proxied - Specify that we only want to compress responses from proxied servers if we normally wouldn’t cache them
  • gzip_types - The Content-Types that we will compress before sending the response
  • gzip_min_length - Adjusting the minimum size of a file that we’ll compress, the default is 20 bytes, but we’re going to not compress resources that are less than one kilobyte
  • gzip_vary - Adds a Vary: Accept-Encoding header. This tells intermediate caches (like CDNs) to treat the compressed and uncompressed version of the same resource as 2 separate entities

What About Decompression

We’re handling on-the-fly compression now, but if one of our proxied servers happens to send us a pre-compressed response then we probably want to decompress it for clients that can’t handle gzip. In this situation, we’ll use the gunzip module, and we’ll place this in the same area as our gzip directives:
/etc/nginx/nginx.conf

  gzip on;
  gzip_disable msie6;
  gzip_proxied no-cache no-store private expired auth;
  gzip_types text/plain text/css application/x-javascript application/javascript text/xml application/xml application/xml+rss text/javascript image/x-icon image/bmp image/svg+xml;
  gzip_min_length 1024;
  gzip_vary on;
  gunzip on;

improve ssl config in nginx

Improving SSL Configuration with SSL Session Caching

Up to this point, when we’ve worked with SSL in our servers, we’ve done the bare minimum by using ssl_certificate and ssl_certificate_key. There are a number of other settings that we can and should set to improve the overall configuration. These improvements are better for security, but can also improve our server performance by alleviating repetitive work.
To begin, let’s add session caching so that fewer SSL handshakes need to be made. The initial handshake is the most taxing part of the process, and if we can avoid repeating it then we’ll improve our overall performance. Let’s make some changes to our /etc/nginx/conf.d/default.conf file to add SSL session caching.
/etc/nginx/conf.d/default.conf (partial)
    ssl_certificate /etc/nginx/ssl/public.pem;
    ssl_certificate_key /etc/nginx/ssl/private.key;

    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;
These three new directives do the following:
  • ssl_session_timeout - set’s how long a session can persist
  • ssl_session_cache - set’s the number of sessions to cache. The shared value indicates that it can be used by all NGINX processes. One megabyte of space can hold about 4,000 sessions
  • ssl_sessions_tickets - SSL Tickets are an idea where encrypted session information is stored on the client instead of the server. We’re opting to not use tickets

Setting SSL Cipher and Protocols

Depending on the clients that will be interacting with a service, the configuration of the TLS protocols and ciphers can be important. For our purposes, we’re expecting that our clients are using modern web browsers (at least IE 11, FireFox 27, Chrome 30, Safari 9, or Android 8). Knowing that we expect “modern” clients we’ll set some values based on suggestions from Mozilla.
/etc/nginx/conf.d/default.conf (partial)
    ssl_certificate /etc/nginx/ssl/public.pem;
    ssl_certificate_key /etc/nginx/ssl/private.key;

    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;

    ssl_protocols TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256';
    ssl_prefer_server_ciphers on;
Note: You can read about these suggestions and more about backward compatibility here.
We know that all of our clients can work with TLS version 1.2 so we’re going to require it using ssl_protocols. Skipping over the ciphers for a moment, we’re setting ssl_prefer_server_ciphers so that we utilize the list of ciphers that we specify rather than using client ciphers. This configuration is so that our server is in control of the SSL/TLS experience, so we’re keeping as much as we can under the server’s umbrella. The ssl_ciphers list is quite long, the ordering is important, and we’re not (at least I’m not) cryptography experts. This list is taken directly from Mozilla as recommended.

HSTS and OCSP Stapling

We only have a few more things to change. The first is adding support for HSTS. HSTS is a way to have NGINX tell the client that it should never interact with our domain using HTTP, and we add this using a header. If we were not ready for our domain/IP address to only receive HTTPS traffic then we should NOT add this header until we are:
/etc/nginx/conf.d/default.conf (partial)
    ssl_certificate /etc/nginx/ssl/public.pem;
    ssl_certificate_key /etc/nginx/ssl/private.key;

    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;

    ssl_protocols TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256';
    ssl_prefer_server_ciphers on;

    # 15768000 is roughly 6 months
    add_header Strict-Transport-Security max-age=15768000;
Now any browser that receives a response from our server will refuse to send traffic over HTTP to our domain for the duration of max-age.
Our last change relates to OCSP or “Online Certificate Status Protocol”. Without OCSP stapling, the client will need to make a separate request to verify the validity of a certificate from the issuer, but with OSCP stapling, the server can make that request and cache it for awhile to return that information with the initial handshake. Let’s add OCSP Stapling:
/etc/nginx/conf.d/default.conf (partial)
    ssl_certificate /etc/nginx/ssl/public.pem;
    ssl_certificate_key /etc/nginx/ssl/private.key;

    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;

    ssl_protocols TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256';
    ssl_prefer_server_ciphers on;

    # 15768000 is roughly 6 months
    add_header Strict-Transport-Security max-age=15768000;

    # OCSP Stapling
    ssl_stapling on;
    ssl_stapling_verify on;
If we check our configuration using nginx -t, we’ll see that we have a warning related to OCSP stapling:
nginx: [warn] "ssl_stapling" ignored, issuer certificate not found for certificate "/etc/nginx/ssl/public.pem"
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Since we’re using a self-signed certificate, the stapling is ineffective. In a setting where we’re using a certificate from an actual certificate authority, we would also want to include the following directive with a downloaded root CA certificate:
/etc/nginx/conf.d/default.conf (partial)
  ssl_trusted_certificate /path/to/ROOT_CA_CERT;

When we discuss using Let’s Encrypt, we’ll generate a valid and verifiable certificate. At that point, we’ll be able to revisit OCSP stapling.

nginx microcaching


we’ll look at an alternative caching strategy that is useful if you have an application with dynamic content that is receiving a lot of traffic.
Note: the commands in this video are run as the root user.

Documentation For This Video

What is “Microcaching”?

If an application or website is updated very frequently, then caching becomes pretty difficult because you don’t know when to remove the cache. If that same application receives a lot of traffic then routing all of that traffic to the application server can overwhelm the server quite quickly. NGINX is good at responding to a lot of traffic, and if the content of the website doesn’t always need to be updated in real-time, then microcaching might be worth using. This is where “microcaching” comes into play. With microcaching, we’re going to cache the contents of requests for just a few seconds, and for the same content, we’ll only send one request every 10 seconds or so to the application server.

Implementing Microcaching

To demonstrate microcaching, we’re going to add it to our UWSGI application and then send a lot of traffic to it. Before we add the caching, let’s install [boom] and see how our application handles a large spike in traffic.
[root] $ pip install boom
With boom installed, we’ll send traffic to https://notes.example.com:
[root] $ boom http://localhost/ --header Host:notes.example.com -c 30 -n 3000
Server Software: nginx/1.12.2
Running GET http://127.0.0.1:80/
        Host: notes.example.com
Running 3000 queries - concurrency 30
[================================================================>.] 99% Done

-------- Results --------
Successful calls                3000
Total time                      15.1118 s
Average                         0.1503 s
Fastest                         0.0444 s
Slowest                         0.1600 s
Amplitude                       0.1157 s
Standard deviation              0.006783
RPS                             198
BSI                             Pretty good

-------- Status codes --------
Code 200                        3000 times.

-------- Legend --------
RPS: Request Per Second
BSI: Boom Speed Index
Sending 3000 total requests using 30 concurrent users 15 seconds. That performance is bad really, but let’s modify the configuration for notes.example.com to see if NGINX can make a difference for us without aggressively caching content like we did for the blog:
/etc/nginx/conf.d/notes.example.com.conf
uwsgi_cache_path /var/cache/nginx/micro levels=1:2
                 keys_zone=micro:10m max_size=1g;

server {
    listen 80;
    server_name notes.example.com;

    uwsgi_cache_key $scheme$request_method$host$request_uri;

    location /static {
        root /var/www/notes.example.com;
    }

    location / {
        add_header X-Cache-Status $upstream_cache_status;
        include uwsgi_params;
        uwsgi_pass unix:/var/run/uwsgi/notes.sock;
        uwsgi_cache micro;
        uwsgi_cache_valid 10s;
    }
}
The main difference between this configuration and the cache we set for the blog is with this line:
uwsgi_cache_valid 10s;
This means we’re only caching content for 10 seconds. Since our original result took more than 10 seconds, we should be able to see a noticeable difference running the same load test. Let’s see what kind of difference the microcaching gives us:
boom http://localhost/ --header Host:notes.example.com -c 30 -n 3000
Server Software: nginx/1.12.2
Running GET http://127.0.0.1:80/
        Host: notes.example.com
Running 3000 queries - concurrency 30
[================================================================>.] 99% Done

-------- Results --------
Successful calls                3000
Total time                      6.4929 s
Average                         0.0595 s
Fastest                         0.0200 s
Slowest                         0.0808 s
Amplitude                       0.0608 s
Standard deviation              0.004789
RPS                             462
BSI                             Pretty good

-------- Status codes --------
Code 200                        3000 times.

-------- Legend --------
RPS: Request Per Second
BSI: Boom Speed Index
Our Requests Per Second (RPS) went from 198 to 462! That’s a huge increase in performance without needing to worry about returning stale content for a long period of time like we potentially could with more aggressive caching.
Knowing how long to cache information is a pretty hard problem to solve. If we have an application that doesn’t deploy very often or that doesn’t display that much dynamic data, then we can be aggressive with caching setting a longer cache_valid time. Microcaching is a good alternative to get some more performance out of your application servers when you do have dynamic content that is allowed to be stale for a short period of time.

nginx simple static caching

Creating a Cache Using fastcgi_cache_path

When we make requests to an application, sometimes the content doesn’t change at all, but in our current reverse-proxy setup we would still pass the request over to the application. We can prevent our application servers from receiving this extra load by having NGINX cache responses and serve that data back when the request matches. NGINX has a powerful caching mechanism built into it and works almost exactly the same regardless of whether you’re using proxy_pass, fastcgi_pass, or uwsgi_pass to proxy to another server. Each of the proxy modules that we’ve looked at so far has equivalent caching directives. We’re going to investigate caching by looking at our WordPress application. Let’s add a simple cache by editing /etc/nginx/conf.d/blog.example.com.conf:
/etc/nginx/conf.d/blog.example.com.conf
fastcgi_cache_path /var/cache/nginx/blog levels=1:2
                   keys_zone=blog:10m size=1g inactive=60m;

server {
    listen 80;
    server_name blog.example.com;

    root /var/www/blog.example.com;
    index index.php;

    fastcgi_cache_key $scheme$request_method$host$request_uri;

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

    location ~ \.php$ {
        fastcgi_index index.php;
        fastcgi_pass unix:/var/run/php-fpm.sock;
        fastcgi_cache blog;
        fastcgi_cache_valid 60m;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}
The first thing to notice is that we had to specify the properties and name of our cache using the fastcgi_cache_path directive. There are a lot of arguments to this directive, so see what they each do:
  • /var/cache/nginx/blog - specifies the directory to store the cached objects
  • levels=1:2 - specifies the number of subdirectory levels used in the cache. This is the recommended setting, yet not the default
  • keys_zone=blog:10m - Allows us to specify the name of the cache and the size of the memory space that will hold the keys and metadata information. The name and size of the lookup table so NGINX can quickly know if a request is a cache hit or miss
  • max_size=1g - Defines the maximum amount of storage we’re allowing NGINX to use for this cache. If not set it will keep caching new keys only limited by storage
  • inactive=60m - Defines the maximum cache lifetime of an item if it’s not accessed again. The cache will be populated on the first hit, and then after that, it will have 60 minutes to receive another request or the item will be removed from the cache
We’ve specified where to cache things, but for fastcgi and uwsgi caching we’ll need to also specify the cache key using the appropriate _cache_key directive. Our cache key is created from the requests scheme, host, method (GET | POST | etc), and request URI.
To see the fruits of the caching, we’re best off to open our browser’s developer tools to look at the network response time and response headers (right-click the page select “Inspect Element” then open the “Network” tab). We’ll reload the page after opening the network tab to see how long each request takes. This gives us the non-cached speed. Now we can reload NGINX before reloading the page to see the difference.
[root] $ systemctl reload nginx

Adding Additional Cache Header

It’s really helpful to know if our request was a cache hit or cache miss. We can display this in the browser’s response information by adding an additional header within our location block. NGINX provides an upstream_cache_status variable that indicates whether the current request is a cache hit or miss. We can set this value as a header using the add_header directive. Let’s add this now:
/etc/nginx/conf.d/blog.example.com.conf
fastcgi_cache_path /var/cache/nginx/blog levels=1:2
                   keys_zone=blog:10m max_size=1g inactive=60m;

server {
    listen 80;
    server_name blog.example.com;

    root /var/www/blog.example.com;
    index index.php;

    fastcgi_cache_key $scheme$request_method$host$request_uri;

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

    location ~ \.php$ {
        add_header X-Cache-Status $upstream_cache_status;
        fastcgi_index index.php;
        fastcgi_pass unix:/var/run/php-fpm.sock;
        fastcgi_cache blog;
        fastcgi_cache_valid 60m;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}
Now when we look at the response headers. We’ll see either “X-Cache-Status: MISS” or “X-Cache-Status: HIT”. This makes debugging caching issues a lot easier.

Not Caching Content

Caching the content of our blog is great, but we don’t want to cache more dynamic content like the admin area of WordPress. Let’s see if what we’ve currently got will cache the admin dashboard pages by going to blog.example.com/wp-login.php. Our “X-Cache-Status” shows a “MISS” the first time, but if we reload the page it doesn’t change to a “HIT”. Why not? NGINX caches responses that are valid, but the proxied server can ensure that it doesn’t happen by returning a “Cache-Control” header that includes “no-cache”.
If we would rather not cache some content without relying on the proxied application, we can do so by creating a more specific location block that doesn’t use fastcgi_cache. There are also conditionals and variables that we can use to indicate whether we’d like to bypass the cache. Here’s an example of how we could bypass the cache if the request includes /wp-admin:
/etc/nginx/conf.d/blog.example.com.conf
fastcgi_cache_path /var/cache/nginx/blog levels=1:2
                   keys_zone=blog:10m max_size=1g inactive=60m;

server {
    listen 80;
    server_name blog.example.com;

    root /var/www/blog.example.com;
    index index.php;

    fastcgi_cache_key $scheme$request_method$host$request_uri;

    set $skip_cache 0;

    if ($request_uri ~* "/wp-admin") {
        set $skip_cache 1;
    }

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

    location ~ \.php$ {
        add_header X-Cache-Status $upstream_cache_status;
        fastcgi_index index.php;
        fastcgi_pass unix:/var/run/php-fpm.sock;
        fastcgi_cache_bypass $skip_cache;
        fastcgi_no_cache $skip_cache;
        fastcgi_cache blog;
        fastcgi_cache_valid 60m;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}
We’re using set and an if context to manipulate a variable before routing the request. If $skip_cache is set to anything other than 0, we can us it with fastcgi_cache_bypass and fastcgi_no_cache to skip checking the cache and not cache the returned response.

Purging the Cache

To get rid of already cached content, we have a few options:
  1. Remove files from disk within our cache directory (/var/cache/nginx/blog in our case).
  2. Utilizing the fastcgi_cache_purge directive.

The first option is self-explanatory, we would use rm -rf to delete the directories under /var/cache/nginx/blog. The second option is more interesting and provides us with a way to programmatically purge the cache. Unfortunately, the documentation shows a fastcgi_cache_purge directive, but it is only part of the commercial distribution, NGINX Plus.

nginx micro caching

What we wanted to achieve in our test configuration was to have a URL like:
http://www.example.com/image/<width>x<height>/<URL>
...that would retrieve the image at:
https://upload.wikimedia.org/<URL>
...then resize it on the fly, cache it and serve it.
Our setup ended up being almost the same as the one in that blog post, with some slight differences.
Requirements installation

First, as the post points out, the Image Filter module is not installed by default on many Linux distributions. As we're using Nginx's official repositories, it was just a matter of installing the nginx_module_image_filter package and restarting the service.
Cache Storage configuration

Continuing following the post's great instructions, we set up the cache in our main http section, tuning each parameter to fit ur specific needs. We wanted a 10MB storage space for keys and 100MB for actual images, that will be removed after not being accessed for 40 days. The main configuration entry was then:

proxy_cache_path /tmp/nginx_cache levels=1:2 keys_zone=nginx_cache:10M max_size=100M inactive=40d;

This went straight in the http section of nginx.conf.
Caching Proxy configuration

Next, we configured our front facing virtual host. In our case, we needed the reverse proxy to live within an already existing site, and that's why we chose the /image/ path prefix.

server {
      ...
 
      location /image/ {
          proxy_pass http://127.0.0.1:20000;
          proxy_cache nginx_cache;
          proxy_cache_key "$proxy_host$uri$is_args$args";
      }
 
      location / {
          # other locations we may need for the site.
          root /var/www/whatever;
      }
 
  }


Every URL starting with /image/ would be server from the cache if present, otherwise it would be proxied to our Resizing Server, and cached for 30 days, as desired.
Resizing Server configuration

We then configured the resizing server, using a regexp to extract the width, height and URL of the image we desire.
The server will proxy the request to https://upload.wikimedia.org/ looking for the image, resize it and then serve it back to the Caching Proxy. We preferred to keep it simple and tidy, as we didn't actually need any aws-related configuration as the blog post did.


Note that we may also use image_filter resize and crop options, should we need different results than just resizing.
Testing the final result

You should now be able to fire up your browser and access an URL like:

http://www.example.com/image/150x150/wikipedia/commons/0/01/Tiger.25.jpg



...and enjoy your caching, resizing, reverse proxying image server.
Optionally securing access to your image server

As this was not a public server, we didn't use any security mechanism to validate the request.
The original blog post, though, reports a very simple and clever way to prevent abuse from unauthorized access, using the Secure Link module.
To access your server you will now need to add an auth parameter to the request, with a secure token that can be easily calculated as an MD5 hash.
This is the simple Bash command we used to test it:
1
echo -n '/image/150x150/wikipedia/commons/0/01/Tiger.25.jpg your_secret' | openssl md5 -binary | openssl base64 | tr +/ -_ | tr -d =


.and the resulting URL would be:
http://www.example.com/image/150x150/wikipedia/commons/0/01/Tiger.25.jpg?auth=TwcXg954Rhkjt1RK8IO4jA

http://blog.endpoint.com/2016/05/caching-resizing-reverse-proxying-image-server-nginx.html

nginx php-fpm wordpress centos 6.x

nginx 1.8
php-fpm 5.3
mysql 5.5
cpu core = 1 , memory = 2G
updated: 2016 April 3

 vim /etc/nginx/nginx.conf  
 user nginx;  
 worker_processes 1;  
 error_log /var/log/nginx/error.log warn;  
 pid    /var/run/nginx.pid;  
 events {  
   worker_connections 1024;  
 }  
 http {  
   include    /etc/nginx/mime.types;  
   default_type application/octet-stream;  
   log_format main '$remote_addr - $remote_user [$time_local] "$request" '  
            '$status $body_bytes_sent "$http_referer" '  
            '"$http_user_agent" "$http_x_forwarded_for"';  
   access_log /var/log/nginx/access.log main;  
   server_tokens off;  
   sendfile    on;  
   tcp_nopush   on;  
   keepalive_timeout 10;  
   #gzip on;  
   # Gzip on  
 gzip on;  
 gzip_min_length 1100;  
 gzip_buffers 4 32k;  
 gzip_types  text/plain application/x-javascript text/xml text/css;  
 ignore_invalid_headers on;  
 client_max_body_size  20m;  
 client_body_buffer_size 15m;  
 client_header_timeout 10s;  
 client_body_timeout 10s;  
 send_timeout   10s;  
 connection_pool_size 256;  
 client_header_buffer_size 4k;  
 large_client_header_buffers 4 32k;  
 request_pool_size 4k;  
 output_buffers  4 32k;  
 postpone_output 1460;  
 # Cache most accessed static files  
 open_file_cache     max=10000 inactive=10m;  
 open_file_cache_valid  2m;  
 open_file_cache_min_uses 1;  
 open_file_cache_errors  on;  
   include /etc/nginx/conf.d/*.conf;  
 }  

vim /etc/nginx/conf.d/default.conf
 server {  
  #for non www to www.domain.com  
   listen    80;  
   server_name  example.com;  
   return    301 http://www.example.com$request_uri;  
 }  
 server {  
   listen    80;  
   server_name www.example.com;  
    root  /var/www/html/example.com/public_html;  
    index index.php index.html index.htm;  
   location / {  
    root  /var/www/html/example.com/public_html;  
    index index.php index.html index.htm;  
    try_files $uri $uri/ /index.php?$args;  
   }  
   location ~ \.php$ {  
         root  /var/www/html/example.com/public_html;  
         try_files $uri =404;  
         include fastcgi_params;  
         fastcgi_pass unix:/var/run/php5-fpm.sock ;  
   fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;  
         fastcgi_index index.php;  
 fastcgi_buffer_size 4K;  
 fastcgi_buffers 64 4k;  
     }  
   location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt)$ {  
     access_log    off;  
     expires      max;  
   }  
   error_page  500 502 503 504 /50x.html;  
   location = /50x.html {  
     root  /usr/share/nginx/html;  
   }  
   location ~ /\.ht {  
     deny all;  
   }  
 }  

/etc/php-fpm.d/www.conf
listen = /var/run/php5-fpm.sock
listen.owner = nginx
listen.group = nginx
listen.mode = 0666



vim /etc/my.cnf

 server {  
  #for non www to www.domain.com  
   listen    80;  
   server_name  example.com;  
   return    301 http://www.example.com$request_uri;  
 }  
 server {  
   listen    80;  
   server_name www.example.com;  
    root  /var/www/html/example.com/public_html;  
    index index.php index.html index.htm;  
   location / {  
    root  /var/www/html/example.com/public_html;  
    index index.php index.html index.htm;  
    try_files $uri $uri/ /index.php?$args;  
   }  
   location ~ \.php$ {  
         root  /var/www/html/example.com/public_html;  
         try_files $uri =404;  
         include fastcgi_params;  
         fastcgi_pass unix:/var/run/php5-fpm.sock ;  
   fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;  
         fastcgi_index index.php;  
 fastcgi_buffer_size 4K;  
 fastcgi_buffers 64 4k;  
     }  
   location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt)$ {  
     access_log    off;  
     expires      max;  
   }  
   error_page  500 502 503 504 /50x.html;  
   location = /50x.html {  
     root  /usr/share/nginx/html;  
   }  
   location ~ /\.ht {  
     deny all;  
   }  
 }  

 
## setup phpmyadmin with basic auth
 
Download phpmyadmin from phpmyadmin.net/downloads (note the php version dependency: im using php 5.3)
 
https://files.phpmyadmin.net/phpMyAdmin/4.4.15.5/phpMyAdmin-4.4.15.5-english.tar.gz 
extract the file and move it to /usr/share as /usr/share/phpMyAdmin
 
   tar xvfz phpMyAdmin-4.4.15.5-english.tar.gz     
   mv phpMyAdmin-4.4.15.5-english /usr/share/phpMyAdmin   
   ln -s /usr/share/phpMyAdmin /var/www/html/example.com/public_html/DBadmin  
 ## Create basic auth file   
   htpasswd -c /var/secret/.htpasswd jimmy   
 #Add a location block in server { ... }  
   location /DBadmin {  
   auth_basic "Admin Login Required";  
   auth_basic_user_file /var/secret/.htpasswd;  
   }   
 
Fix phpmyadmin error 

Error during session start; please check your PHP and/or webserver log file and configure your PHP installation properly. Also ensure that cookies are enabled in your browser.

This error on my case was due to incorrect php session directory where root:apache was the default file ownership
 
ls -l /var/lib/php/
drwxrwx---. 2 root apache 4096 Mar  1 08:02 session

The FIX 

chown root:nginx /var/lib/php/session           
Remove old session files inside /var/lib/php/session
    
 
https://stavrovski.net/blog/install-and-configure-nginx-mysql-php-fpm-in-centos-6
https://www.scalescale.com/tips/nginx/improving-wordpress-performance-nginx-php-fpm-mysql-memcached-w3-total-cache/ 

ispconfig 3 phpmyadmin 404 not found error


ln -s /usr/share/phpmyadmin /var/www/
service nginx restart

mysupermarket.com/phpmyadmin

enter user/password and login...this will redirecto below url

http://mysupermarket.com/index.php?token=81d1f26028dc0f0f625803c2d1ccd402

it will still give

ERROR 404 - Not Found!
The following error occurred:
The requested URL was not found on this server.
Please check the URL or contact the webmaster.

insert phpmyadmin between domain.com and index.php.... like below
http://mysupermarket.com/phpmyadmin/index.php?token=81d1f26028dc0f0f03c2d1ccd402#PMAURL:server=1&target=main.php&token=81d1f26028dc0f0f625803c2d1ccd402










still need to fix....


Nginx brief introduction

why exactly is nginx so much faster than the typical Apache setup of the prefork MPM and mod_php? The technical explanation is that nginx is a non-blocking event based architecture while Apache is a blocking process based architecture. To simplify it heavily the theory is like this:

Apache "Prefork Processes":

    Receive PHP request, send it to a process.
    Process receives the request and pass it to PHP.
    Receive an image request, see process is busy.
    Process finishes PHP request, returns output.
    Process gets image requests and returns the image.

While the process is handling the request it is not capable of serving another request, this means the amount of requests you can do simultaneously is directly proportional to the amount of processes you have running.
Apache + PHP setup has the PHP binary embedded directly into the Apache processes. This means Apache can talk to PHP incredibly fast and without much overhead, but it also means that the Apache process is going to be 25-50MB in size. Not just for requests for PHP requests, but also for all static file requests. This is because the processes keep PHP embedded at all times due to cost of spawning new processes. This effectively means you will be limited by the amount of memory you have as you can only run a small amount of processes and a lot of image requests can quickly make you hit your maximum amount of processes.

Nginx "Event Based Processing:"

    Receive request, trigger events in a process.
    The process handles all the events and returns the output


Nginx
Nginx, on the other hand, requires the use of PHP-FPM if you want to run a PHP application. It
doesn’t have a module to load in PHP like Apache can. I always use Nginx, as it does everything I
need with a simpler configuration, and better overall performance.

Process Management
PHP-FPM’s master process creates child processes to handle all PHP requests. Processes are
expensive to create and manage. How we treat them is important.
PHP-FPM is an implementation of FastCGI, which uses “persistent processes”. Rather than killing
and re-creating a process on each request, FPM will re-use processes.
This is much more efficient than Apache’s mod_php, which requires Apache to create and destroy a
process on every request.

nginx –s stop Stops the daemon immediately (using the TERM signal)
nginx –s quit Stops the daemon gracefully (using the QUIT signal)
nginx –s reopen Reopens the log files
nginx –s reload Reloads the configuration