How to set up smartphones and PCs. Informational portal
  • home
  • Adviсe
  • Nginx: setup and installation. Tweaking Nginx

Nginx: setup and installation. Tweaking Nginx

Good afternoon!

Yes, in my opinion, Nginx is several times faster than the Apache server. Some will object - because Apache can be optimized and it will also become fast. This is true, but we must not forget that Nginx can be very overclocked. I will definitely write a separate article about optimization in detail.

Some theory about Nginx + php-fpm

In the Apache web server, php is a plug-in, such a bundle is slow and consumes a lot of resources. Due to this unfortunate architecture, Apache usually cannot handle more than 200-300 requests per second, even on a very powerful server. In Nginx, a different architecture is used - the Nginx web server itself processes only requests for statics (images, css, etc.), and php execution is given to another software server - php-fpm. Php-fpm (FastCGI Process Manager) is a completely standalone software that can be installed on the same server as Nginx (for small projects) or placed on a separate server. Large projects usually serve several servers with Nginx, php-fpm and databases.

By replacing the Apache server with Nginx + php-fpm, you can speed up the processing of user requests and save a lot on hardware. A web project with a traffic of up to 10,000 unique visitors per day will be able to live on the cheapest virtual server from DigitalOcean for $5 per month. By the way, if you follow this link - DigitalOcean, you will receive $10 upon registration, which is 2 months of using a virtual server. There are no additional conditions for this.

But let's get down to business. I will describe the installation and configuration process using CentOS 6.x as an example, but it will not differ much for other Linux distributions.

Nginx installation:

  • /var/run/php5-fpm.sock should already be present on the server? in ubuntu 16.04 didn't find such file in /var/run
  • 1. Installing the Nginx repository: Standard Linux distributions do not have an Nginx distribution by default, so let's add it to the system.

    vi /etc/yum.repos.d/nginx.repo


    name=nginx repo
    baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
    gpgcheck=0
    enabled=1

    Then press ":wq" and Enter to save and exit. That's it, now Nginx is available for automatic installation through the yum package manager. If you are using a different Linux distribution, go to for instructions specific to your system.

    2. Installing Nginx from the repository: now just run the install command.

    php-fpm installation:

    Php-fpm is available on all modern distributions by default, so just install:

    This will install the server itself and all supporting packages. If something doesn't work, you can build php-fpm from sources yourself, for detailed instructions go here.

    Setting up and running Nginx + php-fpm:

    1. Let's start with php-fpm: open the config file

    vi /etc/php-fpm.d/www.conf

    and write the work through the socket there (it will work faster this way):

    listen = /var/run/php5-fpm.sock

    change the existing "listen =" line, or add a new one and remove the old one.

    2. Now let's move on to Nginx: create a config file for your first site (replace site1 with the name of the site, although it will still work)

    vi /etc/nginx/conf.d/site1.conf

    Below is the minimum configuration, you can just copy it. Everything that needs to be replaced is highlighted in red. In this configuration, the return of static files and access to one php file - index.php is configured. All modern CMS are launched with one file, so this configuration is suitable for most tasks. If you need to run other php files, write them separately. In this configuration, the site files must be placed in the /home/mysite/public_html/ folder

    server(
    listen [server ip address] :80;
    server_name site ;
    resolver 8.8.8.8;
    error_log /var/log/nginx/site _error.log warn;
    root /home/site/public_html;
    access_log /var/log/nginx/site -access.log;
    charset utf-8;
    index index.php;
    location ~ .*(gif|jpg|jpeg|png|ico|swf|txt|pdf|doc|docx|exe|xls|xlsx|strings|zip|rar|7z)$ (
    expires 1y;
    }

    Location ~ .*(html|htm|js|css)$ (
    expires 1y;
    }

    location ~ ^/index.php (
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_param SCRIPT_FILENAME /home/site/public_html/index.php;
    include /etc/nginx/fastcgi_params;
    fastcgi_param SCRIPT_NAME /index.php;
    }

    Now put your first site's files in the /home/site1 /public_html/ folder and we're ready to go.

    3. Starting nginx + php-fpm:

    service nginx start

    service php-fpm start

    If you did everything correctly and did not make a mistake anywhere, the result will be like this:

    If you have any questions or need clarification - please ask a question or leave a comment.

    I'm always happy to help!

    |

    Nginx is one of the most popular web servers in the world, allowing you to host very large sites with high traffic. It tends to use fewer resources than Apache. It can also be used as a reverse proxy.

    This guide will help you install Nginx on an Ubuntu 16.04 server.

    Requirements

    • Ubuntu Server 16.04.
    • Non-root user with access to the sudo command (more on this in).

    Step 1 Install Nginx

    The Nginx package is available in the standard Ubuntu system repository.

    Since this is the first interaction with the apt packaging system in the current session, the package index needs to be updated. After that, you can install Nginx.

    sudo apt-get update
    sudo apt-get install nginx

    The package manager will then install the web server and all of its dependencies.

    Step 2: Firewall Setup

    Before starting Nginx, you need to configure the firewall to support Nginx traffic. During installation, Nginx is registered as a service with ufw, so allowing web server traffic is very easy.

    Open the list of ufw application settings:

    sudo ufw app list

    The command will return:

    Available applications:
    Nginx Full
    Nginx HTTP
    Nginx HTTPS
    OpenSSH

    As you can see, there are three Nginx profiles in the list:

    • Nginx Full: This profile opens port 80 (unencrypted network traffic) and 443 (encrypted TLS/SSL traffic).
    • Nginx HTTP: profile for unencrypted HTTP traffic on port 80.
    • Nginx HTTPS: profile for encrypted TLS/SSL traffic on port 443.

    To enable a profile, enter:

    sudo ufw allow "nginx HTTP"

    Make sure the profile is enabled:

    The command should report that HTTP traffic is allowed:

    status: active
    To Action From
    -- ------ ----
    OpenSSH ALLOW Anywhere
    Nginx HTTP ALLOW Anywhere
    OpenSSH (v6) ALLOW Anywhere (v6)
    Nginx HTTP (v6) ALLOW Anywhere (v6)

    Step 3: Testing the Web Server

    Once installed, Ubuntu 16.04 will start Nginx automatically. At this point, the web server should be up and running.

    To verify that Nginx is running, query its state in the systemd init system.

    systemctl status nginx
    nginx.service - A high performance web server and a reverse proxy server
    Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
    Active: active (running) since Mon 2016-04-18 16:14:00 EDT; 4min 2s ago
    Main PID: 12857 (nginx)
    CGroup: /system.slice/nginx.service
    ├─12857 nginx: master process /usr/sbin/nginx -g daemon on; master_process on
    └─12858 nginx: worker process

    As you can see, the service has been successfully launched.

    You can also try visiting the default Nginx landing page. It is available in the browser by domain name or IP address.

    If you don't know your IP address, you can find it out using the command line. Enter:

    ip addr show eth0 | grep net | awk "( print $2; )" | sed "s/\/.*$//"

    The command will return multiple lines. Check each address in the browser.

    You can also find out how other points on the network see your IP address.

    sudo apt-get install curl
    curl-4 icanhazip.com

    Once you know your IP, type it into your browser to make sure the web server is working properly.

    http://server_domain_or_IP

    The standard Nginx landing page should appear on the screen:

    Welcome to nginx!
    If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

    Step 4: Managing Nginx Processes

    Consider a few basic programs for managing a web server.

    To stop Nginx, type:

    sudo systemctl stop nginx

    To run, type:

    sudo systemctl start nginx

    To restart use the command:

    sudo systemctl restart nginx

    To update Nginx settings without dropping the connection, issue the command:

    sudo systemctl reload nginx

    By default, Nginx starts automatically when the server boots. This behavior can be disabled:

    sudo systemctl disable nginx

    To restart the autostart service, type:

    sudo systemctl enable nginx

    Step 5: Nginx Files and Directories

    Now you know how to manage the service. It's time to familiarize yourself with important Nginx files and directories.

    Content

    • /var/www/htm: This directory contains the current site content. By default, it contains only the standard landing page that you have already seen. This directory can be changed in the Nginx configuration file.

    Server settings

    • /etc/nginx: nginx settings directory where all configuration files are stored.
    • /etc/nginx/nginx.conf: The main Nginx configuration file containing global web server settings.
    • /etc/nginx/sites-available: A directory that stores the configured server blocks (virtual hosts) of each individual site. Nginx will not use these blocks until a link to them appears in the sites-enabled directory (which will be discussed later). Typically, this directory is used to set up virtual hosts.
    • /etc/nginx/sites-enabled/: directory that stores enabled server blocks. To include a block, you need to create a symbolic link to a file stored in the sites-available directory.
    • /etc/nginx/snippets: This directory stores snippets of settings that can be included in the Nginx configuration. Typically, potentially repeatable configuration segments are added as fragments.

    Logs

    • /var/log/nginx/access.log: This log logs all requests received by the Nginx web server (unless otherwise configured).
    • /var/log/nginx/error.log: This log stores all Nginx error messages.

    Conclusion

    The Nginx web server is now installed and ready to go. Use it to serve your site's content.

    Hello, dear Habrahabr user. My story will be about how to prepare the ground for local web development projects in the Ubuntu 16.04.1 LTS operating system.

    In this article, I would like to dispel and explain the possible difficulties associated with installing and configuring the software that is required for modern web development, which novice developers and not only may face.

    Technologies that will be used in the article: nginx, php-fpm.

    Before starting the story, I want to note that I did all these actions on a “bare” system.
    I will be working with the aptitude package manager. I also recommend updating the package index and the packages themselves before installing the software. In this article, we will do these steps together.

    Go!

    Installing the package manager aptitude, update index and packages

    Install:

    sudo apt install aptitude
    We update the index.

    sudo aptitude update
    Update packages (the command will update all packages for which there are new versions, if it is necessary to remove packages, then it will be performed).

    sudo aptitude full-upgrade

    Installation and setup nginx(version >= 1.10.0)

    We install.

    sudo aptitude install nginx
    We launch.

    Sudo service nginx start
    We check the version to make sure that we did not install the old one, that is, below 1.10.0.

    We have done the installation and launch, now let's go to the directory where our nginx is installed and look at its structure. The nginx directory is in this path:

    cd /etc/nginx/
    You can view the contents of the directory with the ls command, with the -la flags it will be more convenient to view the contents of the directory (in fact, this command with specific flags can be described in more detail and more accurately, but we have a different topic today).

    Ls-la
    We are currently interested in two directories that you see in the screenshot. These are the sites-available and sites-enabled directories.

    Let's move into the sites-available directory and start configuring our virtual host (site).

    cd /etc/nginx/sites-available
    Before starting to create a configuration file, let's check what we have in this directory. In my case, the directory is not empty, it already contains configuration files, I erased them so as not to mislead you.

    Important Digression

    In the case of installing nginx "from scratch", it is "from scratch", since when removing nginx with the command
    sudo apt-get remove nginx or sudo apt remove nginx configuration files remain, and if you suddenly don’t understand why nginx doesn’t work and want to reinstall it (usually novice Linux users resort to this), then after reinstallation it will not work correctly, due to the fact that the old configuration files (they are not removed after removal by the remove command) contain incorrect settings, they will have to be removed or configured correctly, only then nginx will work.

    I recommend deleting with the command sudo apt-get purge nginx or sudo apt purge nginx . If you are using the aptitude package manager, then sudo aptitude purge nginx removes the entire package, including all dependencies and configuration files.


    There will be one file in this directory by default, called default. It will contain a configuration file with an example, with comments, you can study it at your leisure, or you can delete it altogether (you can always refer to the official documentation).

    Ls-la

    Let's create our own configuration file that will match the domain name of our local site (or the real one, if you already know its name). This is convenient, in the future, when there will be a lot of configuration files, this will save you from confusion in them. At me this file will be called project.local.

    Sudo touch project.local
    Let's see what happened.

    Now let's open it in the editor, I'll open it in nano.

    Sudo nano project.local
    We see that it is empty. Now let's move on to the formation of our file. You need to bring the configuration to the form as written below. I will describe only the vital directives of this file, I will not describe the rest, since this is not important at the moment, after all, we have a basic configuration topic. These “hill” settings are enough for developing projects locally, not only small ones, but also quite large ones. In the following articles, I will describe separately each directive used (this is how the lines are called, for example, server_name) of this file.

    See the comments right in the configuration file.

    Server ( listen 80; # port listening on nginx server_name project.local; # domain name related to the current virtual host root /home/stavanger/code/project.local; # directory where the project is located, path to the entry point index index. php; # add_header Access-Control-Allow-Origin *; # serve static files directly location ~* \.(jpg|jpeg|gif|css|png|js|ico|html)$ ( access_log off; expires max; log_not_found off ; ) location / ( # add_header Access-Control-Allow-Origin *; try_files $uri $uri/ /index.php?$query_string; ) location ~* \.php$ ( try_files $uri = 404; fastcgi_split_path_info ^(.+ \.php)(/.+)$; fastcgi_pass unix:/var/run/php/php7.0-fpm.sock; # connect php-fpm socket fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; ) location ~ /\.ht ( deny all; ) )
    We save the file. Now we need to check if there are any errors in it. We can do this as a team.

    Sudo nginx -t
    If we see such information as in the screenshot, then everything is correct with us, we can continue setting up. If you get any errors, it's worth double-checking the config file.

    Now we need to activate the configuration file, in the /etc/nginx/sites-enabled/ directory we need to create a symlink (symbolic link). If you have nginx installed "from scratch", then in this directory there is a symlink to the default file, which was described above, you can delete it if you do not need it. We pass to the necessary directory.

    cd /etc/nginx/sites-enabled/
    We are now in the correct directory. Let's create our symlink. To create, use the ln command with the -s flag, then we will specify the path to our project.local config.

    sudo ln -s /etc/nginx/sites-available/project.local
    Let's look at our created symlink.

    To make sure that we are still doing everything right, we will run the command again.

    File hosts

    This file is located in /etc/hosts. The presence of entries in it allows you to run nginx using localhost as the domain. In this file, you can assign alternative aliases, for example, for our project project.local, we will assign the project.local domain.

    Open the file in the nano editor.

    sudo nano /etc/hosts
    You will have other information in this file, just ignore it. You just need to add a line like in my screenshot.

    Installation php-fpm (>=7.0)

    sudo aptitude install php-fpm
    We check the installed version, just in case, although in Ubuntu 16.04.1 the 7.0 version is in the repositories.

    php-fpm7.0 -v

    We make sure everything is ok. Let's start php-fpm.

    sudo service php7.0-fpm start
    If you edit the configs, then do not forget to restart the daemon. It does so. But we won't need it.

    sudo service php7.0-fpm restart
    This completes the installation and configuration of php-fpm. True, that's all. This is not magic, the path to the php-fpm socket has already been specified in the configuration file. Of course, you may need some php extensions for developing personal projects, but you can supply them as they are required.

    Now let's go to the directory with our project, I have it on this path.

    Cd /home/stavanger/code/project.local
    Let's go up to the directory above and set the permissions to 777 (that is, we will make full permissions to the directory with our project.local project). In the future, this will save us from unnecessary problems.

    Cd .. sudo chmod -R 777 project.local
    This completes the software setup, let's create a test file in our project.local working directory and make sure everything works. I will create an index.php file with this content.

    We go to the browser and see that everything works fine for us! PHP interpreter included.

    Yours faithfully to readers, Stavanger.

    The Nginx web server is one of the most popular web servers with very high performance and fast handling of static requests from users. When properly configured, very high performance can be achieved from this web server. Nginx handles static files very quickly, be it html pages or other types of resources.

    In one of the previous articles, we have already considered the configuration of its main parameters, in the same article I want to dwell more on the performance and preparation of the web server for use in combat conditions. As for the Linux distribution, today we will consider CentOS, this system is often used on servers and there may be some difficulties with setting up Nginx. Next, we will consider setting up Nginx CentOS, let's talk about how to enable full support for http2, google pagespeed, and set up the main configuration file.

    The official CentOS repositories have Nginx and it is most likely already installed on your system. But we want the site to work using the http2 protocol, which allows you to transfer all data in one connection, and this increases performance. To work on http2, you will need to configure an SSL certificate, but this is already described in the article Obtaining a Lets Encrypt Nginx Certificate. But that is not all. Most browsers now use the ALPN protocol to switch from regular SSL to HTTP2.0, and it has been supported since OpenSSL 1.02. While the repositories only have OpenSSL 1.01. Therefore, we need to install a version of Nginx built with OpenSSL 1.02. Broken Repo can be used for this:

    sudo yum -y install yum-utils
    # sudo yum-config-manager --add-repo https://brouken.com/brouken.repo

    If you are using the EPEL repository, then you need to specify that you do not need to take Nginx from it:

    sudo yum-config-manager --save --setopt=epel.exclude=nginx*;

    Now, to install the correct version of Nginx, just type:

    sudo yum install nginx

    The latest version of Nginx 1.13.2 will be installed, with full ALPN support. Let's move on to the setup.

    2. Setting up Nginx

    The first step is to consider the structure of the configuration file. At first glance, everything here may seem very confusing, but everything is quite logical there:

    global options
    events()
    http(
    server(
    location()
    }
    server()
    }

    First there are global options that set the main parameters of the program, for example, from which user it will be launched and the number of processes. There is a section next. events, which describes how Nginx will respond to incoming connections, followed by a section http, which combines all the settings regarding the operation of the http protocol. It contains a section server, each such section is responsible for a separate domain, the server section contains sections location, each of which is responsible for a specific request URL, note that not a file on the server, as in Apache, but the request URL.

    We will make the main global settings in the /etc/nginx/nginx.conf file. Next, consider what exactly we will change and what values ​​it is desirable to set. Let's start with global options:

    • user- the user under whose name the server will be launched must be the owner of the directory with the site files, and php-fpm must be launched on behalf of him;
    • worker_processes- the number of Nginx processes that will be launched must be set exactly as many as you have cores, for example, I have 4;
    • worker_cpu_affinity- this parameter allows you to assign each process to a separate processor core, set the value to auto so that the program itself chooses what and what to attach to;
    • worker_rlimit_nofile- the maximum number of files that the program can open, for each connection you need at least two files and each process will have the number of connections you specified, so the formula is: worker_processes* worker_connections* 2, parameter worker_connections we will analyze a little lower;
    • pcre_jit- enable this option to speed up the processing of regular expressions using JIT compilation;

    In the events section, you should configure two parameters:

    • worker_connections- the number of connections for one process must be sufficient to process incoming connections. First we need to know how many of these incoming connections there are, for this we look at the statistics at the ip_server/nginx_status address. How to enable see below. In the Active Connections line, we see the number of active connections to the server, you also need to take into account that connections with php-fpm are also counted. Next, pay attention to the fields accepted and handled, the first one displays the processed connections, the second - the number of accepted ones. From values ​​must be the same. If they differ, then there are not enough connections. See examples, the first picture is the problem, the second is the order. For my configuration, the figure of 200 connections may be optimal (800 in total, considering 4 processes):

    • multi_accept- allows the program to accept several connections at the same time, also speeds up the work, with a large number of connections;
    • accept_mutex- set the value of this parameter to off, so that all processes immediately receive a notification about new connections;

    It is also recommended to use the use epoll directive in the events section, since this is the most efficient method for handling incoming connections for Linux, but this method is used by default, so I see no reason to add it manually. Consider a few more parameters from the http section:

    • sendfile- use the sendfile data sending method. The most efficient method for Linux.
    • tcp_nodelay, tcp_nopush- sends headers and request body in one packet, works a little faster;
    • keepalive_timeout- timeout for maintaining a connection with the client, if you do not have very slow scripts, then 10 seconds will be enough, set the value as long as necessary so that the user can be connected to the server;
    • reset_timedout_connection- disconnect connections after timeout.
    • open_file_cache- cache information about open files. For example, open_file_cache max=200000 inactive=120s; max - the maximum number of files in the cache, caching time.
    • open_file_cache_valid- when you need to check the relevance of files. For example: open_file_cache_valid 120s;
    • open_file_cache_min_uses- cache only files that have been opened the specified number of times;
    • open_file_cache_errors- remember file opening errors.
    • if_modified_since- sets how the if-modified-since headers will be processed. With this header, the browser can get a 304 response if the page hasn't changed since the last time it was viewed. There are options - do not send - off, send if the time exactly matches - exact, send if the time matches exactly or more - before;

    This is how the nginx conf setup will look like:

    user nginx;
    worker_processes 4;
    worker_cpu_affinity auto;
    worker_rlimit_nofile 10000;
    pcre_jit on;

    error_log /var/log/nginx/error.log warn;
    load_module "modules/ngx_pagespeed.so";

    events (
    multi_accept on;
    accept_mutex off;
    worker_connections 1024;
    }

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;

    open_file_cache max=200000 inactive=20s;
    open_file_cache_valid 120s;
    open_file_cache_errors on;

    reset_timedout_connection on;
    client_body_timeout 10;
    keepalive_timeout 65;

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

    3. http2 setup

    I will not describe in detail the configuration of the server section, because I already did it in the article installing Nginx in Ubuntu and I have nothing to add here, configuring SSL is a fairly extensive topic and will also be discussed in a separate article. But to set up http2 you need to have SSL already. Next, just tweak the listen directive in your server section:

    listen 194.67.215.125:443 default_server;

    listen 194.67.215.125:443 http2 default_server;

    Here is a simple way to enable http2 if the correct version of Nginx was installed before.

    4. Setting PageSpeed

    Google Pagespeed is an Nginx module that performs various optimizations to make pages load faster, the web server works more efficiently, and users feel comfortable. This includes caching, html code optimization, image optimization, combining javascript and css code, and much more. All this is done at the Nginx level, so it's more efficient than if you did it in php. But there is one drawback, the module removes the Last Modified header.

    The fact is that PageSpeed ​​sets a very long caching line for all files, and adds its hash to the file name. This makes resource loading much faster, as the browser will only request files with the new hash, and LastModified is removed so that users can see the changes if any file is modified. Now let's look at how to install the module. We will have to build it from source.

    First install the build tools, it's very important, if you don't install it, then you will get an error and you won't know what to do:

    yum install wget gcc cmake unzip gcc-c++ pcre-devel zlib-devel

    Download and extract the Nginx sources for your version, for example 1.13.3:

    wget -c https://nginx.org/download/nginx-1.13.3.tar.gz
    # tar -xzvf nginx-1.13.3.tar.gz

    Setting up the nginx server does not include rebuilding and replacing the program from the repository, we just use these sources to build the module. Download and extract the PageSpeed ​​sources:

    wget -c https://github.com/pagespeed/ngx_pagespeed/archive/v1.12.34.2-stable.zip
    # unzip v1.12.34.2-stable.zip

    Download and unzip the PageSpeed ​​optimization library into the module source folder:

    cd ngx_pagespeed-1.12.34.2-stable/
    # wget -c https://dl.google.com/dl/page-speed/psol/1.12.34.2-x64.tar.gz
    # tar -xvzf 1.12.34.2-x64.tar.gz

    Download and extract OpenSSL 1.02 sources:

    wget -c https://www.openssl.org/source/openssl-1.0.2k.tar.gz -O /opt/lib/$OPENSSL.tar.gz
    # tar xvpzf openssl-1.0.2k.tar.gz

    Now we need to build the module. First, let's look at the options that the current Nginx is built with:

    And now we go to the folder with Nginx, substitute all the received options, the --add-dynamic-module option for PageSpeed, OpenSSL and try to build:

    cd nginx-1.13.3
    # ./configure --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx .conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx .pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache /nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path= /var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --wit h-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt="-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic" --with-ld-opt= --with -openssl=$HOME/openssl-1.0.2k --add-dynamic-module=$HOME/ngx_pagespeed-1.12.34.2-stable $(PS_NGX_EXTRA_FLAGS)
    #make

    If everything was done correctly, then at the output you will get the ngx_pagespeed.so module in the obj folder, you need to copy it to the /etc/nginx/modules folder:

    cp ngx_pagespeed.so /etc/nginx/modules/ngx_pagespeed.so

    Create a folder for the cache:

    mkdir -p /var/ngx_pagespeed_cache
    # chown -R nginx:nginx /var/ngx_pagespeed_cache

    Now add this line to enable the module in /etc/nginx/nginx.conf:

    load_module "modules/ngx_pagespeed.so";

    Nginx is one of the most popular web servers in the world and is used to host the largest and busiest sites on the Internet. Nginx is overwhelmingly less resource intensive than Apache; it can be used both as a web server and as a reverse proxy (reverse proxy).

    In this article, we will walk through the process of installing Nginx on your Ubuntu 16.04 server.

    Before installation

    Before you start following the steps in this article, make sure you have a regular non-root user with sudo privileges. You can learn how to set up such a user on your server from.

    After you have created such a user, log into the server using his username and password. You are now ready to follow the steps in this article.

    Step 1: Installing the Nginx Web Server

    Nginx is available in the standard Ubuntu repositories, so installing it is quite easy.

    Since we are going to use apt for the first time in this session, let's start by updating the local package list. Next, install the server:

    • sudo apt-get update
    • sudo apt-get install nginx

    As a result of executing these commands, apt-get will install Nginx and other packages necessary for it to work on your server.

    Step 2: Firewall setup

    Before we can start testing Nginx, we need to configure our firewall to allow access to the service. When installed, Nginx registers itself with the ufw firewall service. Therefore, setting up access is quite simple.

    To display access settings for applications registered in ufw , enter the command:

    • sudo ufw app list

    As a result of executing this command, a list of application profiles will be displayed:

    Available applications: Nginx Full Nginx HTTP Nginx HTTPS OpenSSH

    As you can see from this output, there are three profiles configured for Nginx:

    • Nginx Full: This profile opens ports 80 (normal, unencrypted web traffic) and 443 (traffic is encrypted with TLS/SSL).
    • Nginx HTTP: This profile only opens port 80 (normal, non-encrypted web traffic).
    • Nginx HTTPS: This profile only opens port 443 (traffic is encrypted with TLS/SSL).

    It is recommended that you configure ufw to only allow traffic that you want to explicitly allow. Since we haven't set up SSL for our server yet, in this article we will only allow traffic on port 80.

    You can do this with the following command:

    • sudo ufw allow "nginx HTTP"

    You can check the changes by issuing the command:

    • sudo ufw status

    This should result in output that looks like this:

    Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere Nginx HTTP ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) Nginx HTTP (v6) ALLOW Anywhere (v6)

    Step 3: Checking the Web Server

    Once the installation process is complete, Ubuntu 16.04 will start Nginx automatically. Therefore, the web server should already be running.

    We can verify this by running the following command:

    • systemctl status nginx
    ● nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled) Active: active (running) since Mon 2016-04-18 16:14:00 EDT; 4min 2s ago Main PID: 12857 (nginx) CGroup: /system.slice/nginx.service ├─12857 nginx: master process /usr/sbin/nginx -g daemon on; master_process on └─12858 nginx: worker process

    As you can see from the output above, the service is up and running. However, we will verify that it is fully operational by requesting a web page.

    To do this, we can check if the Nginx web page is displayed, available by default when entering the domain name or IP address of the server.

    If you don't want to set up a domain name for your server, you can use your server's public IP address. If you don't know the server's public IP address, you can find that IP address with the following command:

    • ip addr show eth0 | grep net | awk "( print $2; )" | sed "s/\/.*$//"

    As a result, several IP addresses will be displayed. Try to paste each of them into the browser.

    Another way to determine your IP address is to check how your server is visible from the Internet:

    • sudo apt-get install curl
    • curl-4 icanhazip.com

    Type the obtained IP address or domain name into your web browser. You should see the default Nginx page.

    http:// domain_name_or_IP_address

    If you see a similar page in your browser, you have successfully installed Nginx.

    Step 4: Managing the Nginx Process

    Now that Nginx is installed and we've verified that it's working, let's take a look at some basic commands to manage our web server.

    To stop the web server, use the command:

    • sudo systemctl stop nginx

    To start a stopped web server, type:

    • sudo systemctl start nginx

    You can use the following command to restart the web server:

    • sudo systemctl restart nginx

    If you make configuration changes to Nginx, you can often restart it without closing connections. To do this, you can use the following command:

    • sudo systemctl reload nginx

    By default, Nginx is configured to start automatically when the server starts. If you do not need this web server behavior, you can disable it with the following command:

    • sudo systemctl disable nginx

    To re-enable Nginx startup at server startup, enter:

    • sudo systemctl enable nginx

    Step 5: Important Nginx Files and Directories

    Now that we know the basic commands for managing a web server, let's take a look at the main directories and files.

    Content

    • /var/www/html: The web content, which by default only consists of the Nginx test page we saw earlier, is in the /var/www/html directory. The path to this directory can be configured in the Nginx configuration files.

    Server configuration

    • /etc/nginx: Nginx configuration directory. All Nginx configuration files are located in this directory.
    • /etc/nginx/nginx.conf: The main Nginx configuration file. This file is used to make changes to the global Nginx configuration.
    • /etc/nginx/sites-available: The directory where the "server blocks" for each site are stored (server blocks are roughly equivalent to virtual hosts in Apache). Nginx will not use configuration files in this directory unless they are properly referenced in the sites-enabled directory (see below). Usually, all server block settings are made in this directory, and then the site is activated by creating a link in another directory.
    • /etc/nginx/sites-enabled/ : Server blocks for enabled sites are stored in this directory. This is usually achieved by creating links to site configuration profiles located in the sites-available directory.
    • /etc/nginx/snippets: This directory contains configuration snippets that can be used to configure any site. Configuration snippets that could potentially be used in multiple configuration files are excellent candidates for creating these snippets.

    Server logs

    • /var/log/nginx/access.log: Every request to your web server is written to this log file, unless otherwise specified by Nginx settings.
    • /var/log/nginx/error.log: Any Nginx errors will be logged to this file.

    Conclusion

    Now that you have a web server installed and configured, you can choose what content to serve to users and what other technologies you can use in addition to the web server.

    Top Related Articles