C4f1151075b447779af31e99d6cf70e2c6eb47ac
By:
newbie

opitmizing nginx on ubuntu 14.04

December 10, 2014 8.1k views

Hello,
i couldn't find any tutorial for nginx optimization on ubuntu 14.04 unless this one which is for debian actually.
https://www.digitalocean.com/community/tutorials/how-to-optimize-nginx-configuration

so i replace codes in my nginx configuration (/etc/nginx/nginx.conf) like this way. could someone confirm i have done it correct or should i change any value as im on the smallest droplet package and installed wordpress (512mb).

please check the bottom part. im actually confused with those 2 http heads

i really appreciate your help guy's

user www-data;
worker_processes 1;
pid /run/nginx.pid;

events {
worker_connections 1024;
# multi_accept on;
}

http {

##
# Basic Settings
##

sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# server_tokens off;

# server_names_hash_bucket_size 64;
# server_name_in_redirect off;

include /etc/nginx/mime.types;
default_type application/octet-stream;

##
# Logging Settings
##

access_log off;
error_log /var/log/nginx/error.log;

##
# Gzip Settings
##

gzip on;
gzip_disable "msie6";

gzip_vary on;
gzip_proxied any;
gzip_comp_level 2;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

##
# nginx-naxsi config
##
# Uncomment it if you installed nginx-naxsi
##

#include /etc/nginx/naxsi_core.rules;

##
# nginx-passenger config
##
# Uncomment it if you installed nginx-passenger
##

#passenger_root /usr;
#passenger_ruby /usr/bin/ruby;

##
# Virtual Host Configs
##

include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;

# snipping other settings for brevity.

#...
client_max_body_size 8m;
#...
}

#mail {
# # See sample authentication script at:
# # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
# # auth_http localhost/auth.php;
# # pop3_capabilities "TOP" "USER";
# # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
# server {
# listen localhost:110;
# protocol pop3;
# proxy on;
# }
#
# server {
# listen localhost:143;
# protocol imap;
# proxy on;
# }
#}

http {

# snipping other settings for brevity.

client_body_timeout 12;
client_header_timeout 12;
keepalive_timeout 15;
send_timeout 10;
}

http {

# client body buffer.

client_body_buffer_size 10K;
client_header_buffer_size 1k;
large_client_header_buffers 2 1k;
}
1 Answer

While the article "How To Optimize Nginx Configuration" was written with Debian in mind, the advice it gives is pretty general and should apply on Ubuntu as well.

Looking at your configuration file above, the one thing that jumps out is that you have multiple http blocks. You should consolidate them by putting every thing that is in a section like:

http {

}

in the same section. Having multiple http blocks could lead to unexpected behavior.

by Alex Kavon
Nginx is a fast and lightweight alternative to the sometimes overbearing Apache 2. However, Nginx just like any kind of server or software must be tuned to help attain optimal performance. Here's how to optimize Nginx configuration.
  • hello,
    thanks for the reply. i tried to put all in one http block as u said but maybe i have done something wrong here. it fails when i restart nginx server

    user www-data;
    worker_processes 1;
    pid /run/nginx.pid;
    
    events {
        worker_connections 1024;
        # multi_accept on;
    }
    
    http {
    
        ##
        # Basic Settings
        ##
    
        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;
        # server_tokens off;
    
        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;
    
        include /etc/nginx/mime.types;
        default_type application/octet-stream;
    
        ##
        # Logging Settings
        ##
    
        access_log off;
        error_log /var/log/nginx/error.log;
    
        ##
        # Gzip Settings
        ##
    
        gzip on;
        gzip_disable "msie6";
    
        gzip_vary on;
        gzip_proxied any;
        gzip_comp_level 2;
        gzip_buffers 16 8k;
        gzip_http_version 1.1;
        gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
    
        ##
        # nginx-naxsi config
        ##
        # Uncomment it if you installed nginx-naxsi
        ##
    
        #include /etc/nginx/naxsi_core.rules;
    
        ##
        # nginx-passenger config
        ##
        # Uncomment it if you installed nginx-passenger
        ##
    
        #passenger_root /usr;
        #passenger_ruby /usr/bin/ruby;
    
        ##
        # Virtual Host Configs
        ##
    
        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
    
        # snipping other settings for brevity.
    
        #...
            client_max_body_size 8m;
        #...
    
        ##
        # snipping other settings for brevity.
        ##
    
        client_body_timeout 12;
        client_header_timeout 12;
        keepalive_timeout 15;
        send_timeout 10;
    
        ##
        # client body buffer.
        ##
    
        client_body_buffer_size 10K;
        client_header_buffer_size 1k;
        large_client_header_buffers 2 1k;
    
    }
    
    
    #mail {
    #   # See sample authentication script at:
    #   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
    # 
    #   # auth_http localhost/auth.php;
    #   # pop3_capabilities "TOP" "USER";
    #   # imap_capabilities "IMAP4rev1" "UIDPLUS";
    # 
    #   server {
    #       listen     localhost:110;
    #       protocol   pop3;
    #       proxy      on;
    #   }
    # 
    #   server {
    #       listen     localhost:143;
    #       protocol   imap;
    #       proxy      on;
    #   }
    #}
    
    
  • Hey! You have two separate values for keepalive_timeout You can only specify that once.

    You can test Nginx configuration files to make sure the file is correct using nginx -t -c /full/path/to/file When I tested yours, this is the output I got:

    # nginx -t -c /etc/nginx/nginx.conf
    nginx: [emerg] "keepalive_timeout" directive is duplicate in /root/foo.conf:86
    nginx: configuration file /etc/nginx/nginx.conf test failed
    
  • @asb
    thanks a lot man for your kind co-operation.

    i have placed all in one place

    #
            # Basic Settings
            ##
    
            sendfile on;
            tcp_nopush on;
            tcp_nodelay on;
            types_hash_max_size 2048;
            client_body_timeout 12;
            client_header_timeout 12;
            keepalive_timeout 15;
            send_timeout 10;
            client_body_buffer_size 10K;
            client_header_buffer_size 1k;
            large_client_header_buffers 2 1k;
            # server_tokens off;
    
    

    now i got this

    mrcm@mrcmanager:~$ sudo nginx -t -c /etc/nginx/nginx.conf
    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successful
    
    

    everything is fine, isnt it?

  • @newbie Looks good! Let us know how it goes.

  • @asb

    i really appreciate your co-operation 1000 times. but im totally noob here and need some more assistance from u.

    next is my nginx server block. i checked server block and found this error with this command
    sudo nginx -t -c /etc/nginx/sites-available/wordpress

    nginx: [emerg] "server" directive is not allowed here in /etc/nginx/sites-available/wordpress:20
    nginx: configuration file /etc/nginx/sites-available/wordpress test failed
    

    heres what i have in my nignx server block

    # You may add here your
    # server {
    #   ...
    # }
    # statements for each of your virtual hosts to this file
    
    ##
    # You should look at the following URL's in order to grasp a solid understanding
    # of Nginx configuration files in order to fully unleash the power of Nginx.
    # http://wiki.nginx.org/Pitfalls
    # http://wiki.nginx.org/QuickStart
    # http://wiki.nginx.org/Configuration
    #
    # Generally, you will want to move this file somewhere, and start with a clean
    # file but keep this around for reference. Or just disable in sites-enabled.
    #
    # Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
    ##
    
    server {
        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;
    
        root /var/www/html;
        index index.php index.html index.htm;
    
        # Make site accessible from http://localhost/
        server_name mrcmanager.com www.mrcmanager.com;
    
        location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            # try_files $uri $uri/ =404;
            try_files $uri $uri/ /index.php?q=$uri&$args;
            # Uncomment to enable naxsi on this location
            # include /etc/nginx/naxsi.rules
        }
    
        error_page 404 /404.html;
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            root /usr/share/nginx/html;
        }
    
        location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
        location ~* .(jpg|jpeg|png|gif|woff|eot|ico|css|js)$ {
        expires 365d;
        add_header Pragma public;
        add_header Cache-Control "public, must-revalidate, proxy-revalidate";
    }
    
        # Only for nginx-naxsi used with nginx-naxsi-ui : process denied requests
        #location /RequestDenied {
        #   proxy_pass http://127.0.0.1:8080;    
        #}
    
        #error_page 404 /404.html;
    
        # redirect server error pages to the static page /50x.html
        #
        #error_page 500 502 503 504 /50x.html;
        #location = /50x.html {
        #   root /usr/share/nginx/html;
        #}
    
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #   fastcgi_split_path_info ^(.+\.php)(/.+)$;
        #   # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
        #
        #   # With php5-cgi alone:
        #   fastcgi_pass 127.0.0.1:9000;
        #   # With php5-fpm:
        #   fastcgi_pass unix:/var/run/php5-fpm.sock;
        #   fastcgi_index index.php;
        #   include fastcgi_params;
        #}
    
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #   deny all;
        #}
    }
    
    
    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #   listen 8000;
    #   listen somename:8080;
    #   server_name somename alias another.alias;
    #   root html;
    #   index index.html index.htm;
    #
    #   location / {
    #       try_files $uri $uri/ =404;
    #   }
    #}
    
    
    # HTTPS server
    #
    #server {
    #   listen 443;
    #   server_name localhost;
    #
    #   root html;
    #   index index.html index.htm;
    #
    #   ssl on;
    #   ssl_certificate cert.pem;
    #   ssl_certificate_key cert.key;
    #
    #   ssl_session_timeout 5m;
    #
    #   ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;
    #   ssl_ciphers "HIGH:!aNULL:!MD5 or HIGH:!aNULL:!MD5:!3DES";
    #   ssl_prefer_server_ciphers on;
    #
    #   location / {
    #       try_files $uri $uri/ =404;
    #   }
    #}
    
    

    could you please tell me where i have made mistake?

    also im using w3tc but i cannon write rewrite rules in my /var/www/html/nginx.conf
    error i got is

    nginx: [emerg] "rewrite" directive is not allowed here in /var/www/html/nginx.conf:2
    nginx: configuration file /var/www/html/nginx.conf test failed
    
    

    this same error i got when i write default w3tc rewrite rules which i got from w3tc install page and when disk enhanced is turned off in both cases.

    #Yoast sitemap {
        rewrite ^/sitemap_index\.xml$ /index.php?sitemap=1 last;
        rewrite ^/([^/]+?)-sitemap([0-9]+)?\.xml$ /index.php?sitemap=$1&sitemap_n=$2 last;
    }
    # BEGIN W3TC Browser Cache
    gzip on;
    gzip_types text/css text/x-component application/x-javascript application/javascript text/javascript text/x-js text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon;
    location ~ \.(css|htc|less|js|js2|js3|js4)$ {
        expires 31536000s;
        add_header Pragma "public";
        add_header Cache-Control "max-age=31536000, public";
        add_header X-Powered-By "W3 Total Cache/0.9.4.1";
    }
    location ~ \.(html|htm|rtf|rtx|svg|svgz|txt|xsd|xsl|xml)$ {
        expires 3600s;
        add_header Pragma "public";
        add_header Cache-Control "max-age=3600, public";
        add_header X-Powered-By "W3 Total Cache/0.9.4.1";
    }
    location ~ \.(asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|json|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|otf|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|tif|tiff|ttf|ttc|wav|wma|wri|woff|xla|xls|xlsx|xlt|xlw|zip)$ {
        expires 31536000s;
        add_header Pragma "public";
        add_header Cache-Control "max-age=31536000, public";
        add_header X-Powered-By "W3 Total Cache/0.9.4.1";
    }
    # END W3TC Browser Cache
    
    

    i know im asking so many things but please help me to learn solving these issues.

  • i think my /var/www/html/nginx.conf is not communication with my server. whatever i write in that file returns with error.

    now i disabled disk:enhanced mode and enabled disk method for page cache.
    see what i get now

    nginx: [emerg] "gzip" directive is not allowed here in /var/www/html/nginx.conf:2
    nginx: configuration file /var/www/html/nginx.conf test failed
    
Have another answer? Share your knowledge.