Ubuntu 12.04 + Nginx 1.2.6 + PHP-FPM server block / vhost example

On the internet there is not a clean and good example that is basic and follows the best practices. Below I created a working server block / vhost or virtual host example that works on Ubuntu 12.04 and Nginx 1.2.6..

Read the page Nginx basic configuration carefully to understand how location directives work, it really explains it well! Especially this part is important:

Directives are processed in the following manner:

server {
    server_name www.example.com;
    return 301 $scheme://example.com$request_uri;

server {
    server_name example.com;

    root /home/openpanel-admin/sites/www.example.com/public_html;
    index index.php index.html index.htm;

    location / {
        # check if request URI is a real file or directory, otherwise do internal rewrite to /index.php
        try_files $uri $uri/ /index.php?$query_string;

    # serve static files directly
    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires 14d;

    # protect files against prying eyes
    location ~* \.(engine|inc|info|install|make|module|profile|test|po|sh|sql|theme|tpl\.php|xtmpl|Entries|Repository|Root|Tag|Template|jar|java|class)$ {
        deny all;

    location ~ \.php$ {
        # 404 error if the PHP file does not exist
        try_files $uri = 404;

        # pass to php5-fpm backend
        include fastcgi_params;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $realpath_root$fastcgi_script_name;
        fastcgi_param  DOCUMENT_ROOT    $realpath_root;
        fastcgi_param  SERVER_ADMIN  "admin@example.com";

        fastcgi_pass unix:/var/run/php5-fpm.sock;

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    location ~ /\.ht {
        deny  all;
Tags: ,