Search for:
Install and Compile “Nginx 1.10.0” (Stable Release) from Sources in RHEL/CentOS 7.0

Install and Compile &-8220;Nginx 1.10.0&-8221; (Stable Release) from Sources in RHEL/CentOS 7.0 &-8211; this Article or News was published on this date:2019-05-28 19:04:31 kindly share it with friends if you find it helpful

Nginx is the most fast growing Webserver today on public internet facing servers due to its free open source modular model, high-performance, stability, simple configurations files, asynchronous architecture (event-driven) and low resources needed to run.

Requirements

For RHEL 7.0
  1. Minimal Installation of RHEL 7.0
  2. Active RedHat Subscription and Repositories on RHEL 7.0
For CentOS 7.0
  1. Minimal Installation of CentOS 7.0
Configure Static IP Address
  1. Set Static IP Address on RHEL/CentOS 7.0

This tutorial will guide you on installing latest stable version of Nginx 1.10.0 on Red Hat Enterprise or CentOS 7 from sources, because official RHEL/CentOS 7 repositories mirrors doesn’t provide a binary package. If you want to avoid sources installation you can add official Nginx repository and install the binary package (available versions is 1.9.x) with the help of Yum Package Manager as shown:

To enable nginx official yum repository for RHEL/CentOS 7, create a file /etc/yum.repos.d/nginx.repo with the following contents:

[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/mainline/centos/7/$basearch/
gpgcheck=0
enabled=1

Replace “centos” with “rhel”, depending on the distribution you’re using and install nginx with yum package manager as shown:

- yum install nginx

Important: Please note, following above official nginx yum repositories will give you older version of nginx, if you really want to build most recent version of Nginx, then i suggest you to follow source installation as shown below.

Using sources compilation and installation has some benefits, due to the fact that you can install the latest version available, you can tweak Nginx configuration by adding or removing modules, change installation system path, or other important settings, in other words, you have a complete control over installation process.

Step 1: Download, Compile and Install Nginx

1. Before starting Nginx compilation and installation process make sure that you have C / C++ compiler, PCRE (Perl Compatible Regular Expressions), Zlib Compression Library and OpenSSL (if you intend to run Nxing with SSL support) packages installed on your machine by issuing the following command.

- yum -y install gcc gcc-c++ make zlib-devel pcre-devel openssl-devel
Install GCC and C++ Compiler
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: centos.mirror.net.in
 * extras: centos.mirror.net.in
 * updates: centos.mirror.net.in
Package 1:make-3.82-21.el7.x86_64 already installed and latest version
Resolving Dependencies
--> Running transaction check
---> Package gcc.x86_64 0:4.8.5-4.el7 will be installed
--> Processing Dependency: libgomp = 4.8.5-4.el7 for package: gcc-4.8.5-4.el7.x86_64
--> Processing Dependency: cpp = 4.8.5-4.el7 for package: gcc-4.8.5-4.el7.x86_64
--> Processing Dependency: libgcc >= 4.8.5-4.el7 for package: gcc-4.8.5-4.el7.x86_64
--> Processing Dependency: glibc-devel >= 2.2.90-12 for package: gcc-4.8.5-4.el7.x86_64
--> Processing Dependency: libmpfr.so.4()(64bit) for package: gcc-4.8.5-4.el7.x86_64
--> Processing Dependency: libmpc.so.3()(64bit) for package: gcc-4.8.5-4.el7.x86_64
---> Package gcc-c++.x86_64 0:4.8.5-4.el7 will be installed
--> Processing Dependency: libstdc++-devel = 4.8.5-4.el7 for package: gcc-c++-4.8.5-4.el7.x86_64
--> Processing Dependency: libstdc++ = 4.8.5-4.el7 for package: gcc-c++-4.8.5-4.el7.x86_64
---> Package openssl-devel.x86_64 1:1.0.1e-51.el7_2.4 will be installed
--> Processing Dependency: openssl-libs(x86-64) = 1:1.0.1e-51.el7_2.4 for package: 1:openssl-devel-1.0.1e-51.el7_2.4.x86_64
--> Processing Dependency: krb5-devel(x86-64) for package: 1:openssl-devel-1.0.1e-51.el7_2.4.x86_64
---> Package pcre-devel.x86_64 0:8.32-15.el7 will be installed
--> Processing Dependency: pcre(x86-64) = 8.32-15.el7 for package: pcre-devel-8.32-15.el7.x86_64
---> Package zlib-devel.x86_64 0:1.2.7-15.el7 will be installed
--> Processing Dependency: zlib = 1.2.7-15.el7 for package: zlib-devel-1.2.7-15.el7.x86_64
...

2. Now go to Nginx official page and grab the latest Stable version (nginx 1.10.0) available using wget command, extract the TAR archive and enter Nginx extracted directory, using the following commands sequence.

- wget http://nginx.org/download/nginx-1.10.0.tar.gz
- tar xfz nginx-1.10.0.tar.gz
- cd nginx-1.10.0/
- ls -all
Download Nginx Source
--2016-03-21 09:30:15--  http://nginx.org/download/nginx-1.10.0.tar.gz
Resolving nginx.org (nginx.org)... 206.251.255.63, 95.211.80.227, 2001:1af8:4060:a004:21::e3
Connecting to nginx.org (nginx.org)|206.251.255.63|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 908954 (888K) [application/octet-stream]
Saving to: ‘nginx-1.10.0.tar.gz’

100%[=====================================================================================================================================================>] 9,08,954    81.0KB/s   in 11s    

2016-03-21 09:30:27 (77.4 KB/s) - ‘nginx-1.10.0.tar.gz’ saved [908954/908954]

3. The next step is customize Nginx installation process. Use the configure file to visualize configuration options and modules needed for your compilation process using the following command and make sure that you are in nginx-1.6.0/ path.

- ./configure --help
Nginx Configure Help
-help                             print this message

  --prefix=PATH                      set installation prefix
  --sbin-path=PATH                   set nginx binary pathname
  --modules-path=PATH                set modules path
  --conf-path=PATH                   set nginx.conf pathname
  --error-log-path=PATH              set error log pathname
  --pid-path=PATH                    set nginx.pid pathname
  --lock-path=PATH                   set nginx.lock pathname

  --user=USER                        set non-privileged user for
                                     worker processes
  --group=GROUP                      set non-privileged group for
                                     worker processes

  --build=NAME                       set build name
  --builddir=DIR                     set build directory

  --with-select_module               enable select module
  --without-select_module            disable select module
  --with-poll_module                 enable poll module
  --without-poll_module              disable poll module

  --with-threads                     enable thread pool support

  --with-file-aio                    enable file AIO support
  --with-ipv6                        enable IPv6 support

  --with-http_ssl_module             enable ngx_http_ssl_module
  --with-http_v2_module              enable ngx_http_v2_module
...

4. Now it’s time to compile Nginx with your specific configurations and enabled or disabled modules. For this tutorial the following modules and specifications where used, but you can tweak the compilation to whatever suits your needs.

  1. –user=nginx –group=nginx => system user and group that Nginx will run as.
  2. –prefix=/etc/nginx => directory for server files (nginx.conf file and other configuration files) – default is /usr/local/nginx directory.
  3. –sbin-path=/usr/sbin/nginx => Nginx executable file location.
  4. –conf-path=/etc/nginx/nginx.conf => sets the name for the nginx.conf configuration file – you can change it.
  5. –error-log-path=/var/log/nginx/error.log => sets Nginx error log file location.
  6. –http-log-path=/var/log/nginx/access.log => sets Nginx access log file location.
  7. –pid-path=/var/run/nginx.pid => sets the name for main process ID file.
  8. –lock-path=/var/run/nginx.lock => sets the name for Nginx lock file.
  9. –with-http_ssl_module => enables building the HTTPS module – not built by default and requires OpenSSL library.
  10. –with-pcre => sets the path to the sources of the PCRE library – not built by default and requires PCRE library.

To view a list of all Nginx modules visit Nginx Wiki web page at http://wiki.nginx.org/Modules.

If you don’t need a specific module installed on Nginx you can disable it using the following command.

--without-module_name

Now start to compile Nginx by issuing the following command, which will use all the configurations and modules discussed above (make sure the command stays on a single line).

- ./configure --user=nginx --group=nginx --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --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 --with-http_ssl_module --with-pcre
Configure Nginx With Modules
checking for OS
 + Linux 3.10.0-229.el7.x86_64 x86_64
checking for C compiler ... found
 + using GNU C compiler
 + gcc version: 4.8.5 20150623 (Red Hat 4.8.5-4) (GCC) 
checking for gcc -pipe switch ... found
checking for -Wl,-E switch ... found
checking for gcc builtin atomic operations ... found
checking for C99 variadic macros ... found
checking for gcc variadic macros ... found
checking for gcc builtin 64 bit byteswap ... found
checking for unistd.h ... found
checking for inttypes.h ... found
checking for limits.h ... found
checking for sys/filio.h ... not found
checking for sys/param.h ... found
checking for sys/mount.h ... found
checking for sys/statvfs.h ... found
checking for crypt.h ... found
checking for Linux specific features
checking for epoll ... found
checking for EPOLLRDHUP ... found
checking for O_PATH ... found
checking for sendfile() ... found
checking for sendfile64() ... found
checking for sys/prctl.h ... found
checking for prctl(PR_SET_DUMPABLE) ... found
checking for sched_setaffinity() ... found
checking for crypt_r() ... found
checking for sys/vfs.h ... found
checking for poll() ... found
checking for /dev/poll ... not found
...

5. After the compilation process verifies all system required utilities like GNU C compiler, PCRE and OpenSSL libraries, it creates the make.conf file and outputs a summary of all configurations.

Nginx Compilation Summary
Configuration summary
  + using system PCRE library
  + using system OpenSSL library
  + md5: using OpenSSL library
  + sha1: using OpenSSL library
  + using system zlib library

  nginx path prefix: "/etc/nginx"
  nginx binary file: "/usr/sbin/nginx"
  nginx modules path: "/etc/nginx/modules"
  nginx configuration prefix: "/etc/nginx"
  nginx configuration file: "/etc/nginx/nginx.conf"
  nginx pid file: "/var/run/nginx.pid"
  nginx error log file: "/var/log/nginx/error.log"
  nginx http access log file: "/var/log/nginx/access.log"
  nginx http client request body temporary files: "client_body_temp"
  nginx http proxy temporary files: "proxy_temp"
  nginx http fastcgi temporary files: "fastcgi_temp"
  nginx http uwsgi temporary files: "uwsgi_temp"
  nginx http scgi temporary files: "scgi_temp"

6. The last step is to build the binaries using make command, which can take some time to finish depending on your machine resources, and install Nginx on your system with make install command.

Be careful that make install requires root privileges to perform the installation, so if you’re not logged in with root account use a privilege user with sudo.

- make
- make install
Run Nginx Make Command
make -f objs/Makefile
make[1]: Entering directory `/root/nginx-1.10.0'
make[1]: Warning: File `src/core/nginx.h' has modification time 3110036 s in the future
cc -c -pipe  -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werror -g  -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs 
	-o objs/src/core/nginx.o 
	src/core/nginx.c
cc -c -pipe  -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werror -g  -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs 
	-o objs/src/core/ngx_log.o 
	src/core/ngx_log.c
cc -c -pipe  -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werror -g  -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs 
	-o objs/src/core/ngx_palloc.o 
	src/core/ngx_palloc.c
cc -c -pipe  -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werror -g  -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs 
	-o objs/src/core/ngx_array.o 
	src/core/ngx_array.c
cc -c -pipe  -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werror -g  -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs 
	-o objs/src/core/ngx_list.o 
	src/core/ngx_list.c
cc -c -pipe  -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werror -g  -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs 
	-o objs/src/core/ngx_hash.o 
	src/core/ngx_hash.c
cc -c -pipe  -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werror -g  -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs 
	-o objs/src/core/ngx_buf.o 
	src/core/ngx_buf.c
cc -c -pipe  -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werror -g  -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs 
	-o objs/src/core/ngx_queue.o 
...
Run Nginx Make Install Command
make -f objs/Makefile install
make[1]: Entering directory `/root/nginx-1.10.0'
make[1]: Warning: File `src/core/nginx.h' has modification time 3109935 s in the future
cc -c -pipe  -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werror -g  -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs 
	-o objs/src/core/nginx.o 
	src/core/nginx.c
cc -c -pipe  -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werror -g  -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs 
	-o objs/src/core/ngx_log.o 
	src/core/ngx_log.c
cc -c -pipe  -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werror -g  -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs 
	-o objs/src/core/ngx_palloc.o 
	src/core/ngx_palloc.c
cc -c -pipe  -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werror -g  -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs 
	-o objs/src/core/ngx_array.o 
	src/core/ngx_array.c
cc -c -pipe  -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werror -g  -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs 
	-o objs/src/core/ngx_list.o 
	src/core/ngx_list.c
cc -c -pipe  -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werror -g  -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs 
	-o objs/src/core/ngx_hash.o 
	src/core/ngx_hash.c
cc -c -pipe  -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werror -g  -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs 
	-o objs/src/core/ngx_buf.o 
	src/core/ngx_buf.c
cc -c -pipe  -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werror -g  -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs 
	-o objs/src/core/ngx_queue.o 
...

Step 2: Tweak Nginx and Create INIT Script

7. After the installation process has finished with success add nginx system user (with /etc/nginx/ as his home directory and with no valid shell), the user that Nginx will run as by issuing the following command.

- useradd -d /etc/nginx/ -s /sbin/nologin nginx
Add Nginx UserAdd Nginx User

Add Nginx User

8. Because on compilation process we had specified that Nginx will run from nginx system user, open nginx.conf file and change the user statement to nginx.

- nano /etc/nginx/nginx.conf

Here locate and change user and, also, document root location statements, with the following options.

user nginx;
location / {
                root /srv/www/html;
                autoindex on;
                index index.html index.htm;
Add Nginx UserRun Nginx as User

Run Nginx as User

Add Nginx UserEnable Nginx DocumentRoot

Enable Nginx DocumentRoot

9. Before starting Nginx, assure that you have created the web document root path, then start nginx using the following command.

- mkdir -p /srv/www/html
- /usr/sbin/nginx

If you want to check if Nginx is running using your shell prompt, run netstat command to verify listen connections.

- netstat -tulpn | grep nginx
Add Nginx UserCreate Nginx DocumentRoot

Create Nginx DocumentRoot

10. To verify it from an remote system, add a Firewall rule to open connection to outside on Port 80, open a browser and direct URL to your server IP Address at http://server_IP.

- firewall-cmd --add-service=http  -- For on-fly rule
- firewall-cmd --permanent --add-service=http  -- For permanent rule
- systemctl restart firewalld
Add Nginx UserVerify Nginx Installation

Verify Nginx Installation

11. To manage Nginx process use the following commands.

  1. nginx -V = displays Nginx modules and configurations
  2. nginx -h = help options
  3. nginx = start Nginx process
  4. nginx -s stop = stop Nginx process
  5. nginx -s reload = reload Nginx process
- nginx -V
Check Nginx Installed Version
nginx version: nginx/1.10.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-4) (GCC) 
built with OpenSSL 1.0.1e-fips 11 Feb 2013
TLS SNI support enabled
configure arguments: --user=nginx --group=nginx --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --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 --with-http_ssl_module --with-pcre

12. If you need to manage Nginx daemon process through a init RHEL/CentOS script, create the following nginx file on /etc/init.d/ system path, and, then, you can use service or systemctl commands to manage the process.

- nano /etc/init.d/nginx

Add the following file content.

-!/bin/sh
-
- nginx - this script starts and stops the nginx daemon
-

- chkconfig:   - 85 15
- description:  Nginx is an HTTP(S) server, HTTP(S) reverse 
-               proxy and IMAP/POP3 proxy server
- processname: nginx
- config:      /etc/nginx/nginx.conf
- pidfile:     /var/run/nginx.pid
- user:        nginx

- Source function library.
. /etc/rc.d/init.d/functions

- Source networking configuration.
. /etc/sysconfig/network

- Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

nginx="/usr/sbin/nginx"
prog=$(basename $nginx)

NGINX_CONF_FILE="/etc/nginx/nginx.conf"
lockfile=/var/run/nginx.lock

start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    echo -n $"Starting $prog: "
    daemon $nginx -c $NGINX_CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}

stop() {
    echo -n $"Stopping $prog: "
    killproc $prog -QUIT
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

restart() {
    configtest || return $?
    stop
    start
}

reload() {
    configtest || return $?
    echo -n $"Reloading $prog: "
    killproc $nginx -HUP
    RETVAL=$?
    echo
}

force_reload() {
    restart
}

configtest() {
  $nginx -t -c $NGINX_CONF_FILE
}

rh_status() {
    status $prog
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}

case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart|configtest)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
            ;;
   *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
        exit 2
esac
Add Nginx UserAdd Nginx Init Script

Add Nginx Init Script

13. After the Nginx init file is created, append executions permissions and manage the daemon using the below command options.

- chmod +x /etc/init.d/nginx
- service nginx start|stop|restart|reload|force_reload|configtest|condrestart
- systemctl start|stop|restart nginx
Add Nginx UserStart Nginx Server

Start Nginx Server

14. If you need to enable Nginx system-wide use the following command to start at boot time.

- chkconfig nginx on

OR

- systemctl enable nginx

That’s all! Now you have latest version of Nginx installed on your RHEL/CentOS 7 system. On the next tutorial I will discuss how to install and enable PHP-FPM process manager though Nginx FastCGI Gateway.

Read Also: The Ultimate Guide to Secure, Harden and Improve Performance of Nginx Web Server

How to Setup Name-based and IP-based Virtual Hosts (Server Blocks) with NGINX

How to Setup Name-based and IP-based Virtual Hosts (Server Blocks) with NGINX &-8211; this Article or News was published on this date:2019-05-28 17:59:04 kindly share it with friends if you find it helpful

In a relatively short period of time since it was developed and made available (a little over 10 years), Nginx has experienced a sustained and steady growth among web servers because of its high performance and low memory usage.

Nginx Name-based and IP-based Virtual HostingNginx Name-based and IP-based Virtual Hosting

Nginx Name-based and IP-based Virtual Hosting

Since Nginx is Free and Open Source Software, it has been adopted by thousands of web server administrators around the globe, not only in Linux and *nix servers, but also in Microsoft Windows.

Don’t Miss: Apache Name-based and IP-based Virtual Hosting

For those of us most used to Apache, Nginx may have a somewhat steep learning curve (at least that was my case) but it certainly pays off once you set up a couple of sites and start seeing the traffic and resource usage statistics.

In this article we will explain how to use Nginx to set up name-based and ip-based virtual hosting in CentOS/RHEL 7 servers and Debian 8 and derivatives, starting with Ubuntu 15.04 and its spin-offs.

Our testing scenario for this article is as follows:

  1. Operating System: Debian 8 Jessie server [IP 192.168.0.25]
  2. Gateway: Router [IP 192.168.0.1]
  3. Web Server: Nginx 1.6.2-5
  4. Dummy Domains: www.sfnewslovesnginx.com and www.nginxmeanspower.com.

Installing Nginx Web Server

If you haven’t done so already, please install Nginx before proceeding further. If you need help to get started, a quick search for nginx in this site will return several articles on this topic. Click on the magnifying glass icon at the top of this page and search for keyword nginx. If you don’t know how to search for articles in this site, don’t worry here we’ve added links to the nginx articles, just go through and install it as per your respective Linux distributions.

  1. Install and Compile Nginx from Sources in RHEL/CentOS 7
  2. Install Nginx Web Server on Debian 8
  3. Install Nginx with MariaDB and PHP/PHP-FPM on Fedora 23
  4. Install Nginx Web Server on Ubuntu 15.10 Server/Desktop
  5. Password Protect Nginx Website Directories

Then get ready to continue with the rest of this tutorial.

Creating Name-based Virtual Hosts in Nginx

As I’m sure you already know, a virtual host is a website that is served by Nginx in a single cloud VPS or physical server. However, in the Nginx docs you will find the term "server blocks" instead, but they are basically the same thing called by different names.

The first step to set up virtual hosts is to create one or more server blocks (in our case we will create two, one for each dummy domain) in the main configuration file (/etc/nginx/nginx.conf) or inside /etc/nginx/sites-available.

Although the name of the configuration files in this directory (sites-available) can be set to whatever you want, it’s a good idea to use the name of the domains, and in addition we chose to add the .conf extension to indicate that these are configuration files.

These server blocks can be relatively complex, but in their basic form they consist of the following content:

In /etc/nginx/sites-available/sfnewslovesnginx.com.conf:

server {  
    listen       80;  
    server_name  sfnewslovesnginx.com www.sfnewslovesnginx.com;
    access_log  /var/www/logs/sfnewslovesnginx.access.log;  
    error_log  /var/www/logs/sfnewslovesnginx.error.log error; 
        root   /var/www/sfnewslovesnginx.com/public_html;  
        index  index.html index.htm;  
}

In /etc/nginx/sites-available/nginxmeanspower.com.conf:

server {  
    listen       80;  
    server_name  nginxmeanspower.com www.nginxmeanspower.com;
    access_log  /var/www/logs/nginxmeanspower.access.log;  
    error_log  /var/www/logs/nginxmeanspower.error.log error;
    root   /var/www/nginxmeanspower.com/public_html;  
    index  index.html index.htm;  
}

You can use the above blocks to start setting up your virtual hosts, or you can create the files with the basic skeleton from /etc/nginx/sites-available/default (Debian) or /etc/nginx/nginx.conf.default (CentOS).

Once copied, change their permissions and ownership:

- chmod 660  /etc/nginx/sites-available/sfnewslovesnginx.com.conf
- chmod 660  /etc/nginx/sites-available/nginxmeanspower.com.conf

Debian and Derivatives

- chgrp www-data  /etc/nginx/sites-available/sfnewslovesnginx.com.conf
- chgrp www-data  /etc/nginx/sites-available/nginxmeanspower.com.conf

CentOS and RHEL

- chgrp nginx  /etc/nginx/sites-available/sfnewslovesnginx.com.conf
- chgrp nginx  /etc/nginx/sites-available/nginxmeanspower.com.conf

When you’re done, you should delete the sample file or rename it to something else to avoid confusion or conflicts.

Please note that you will also need to create the directory for the logs (/var/www/logs) and give the Nginx user (nginx or www-data, depending on whether you are running CentOS or Debian) read and write permissions over it:

- mkdir /var/www/logs
- chmod -R 660 /var/www/logs
- chgrp nginx user> /var/www/logs

The virtual hosts must now be enabled by creating a symlink to this file in the sites-enabled directory:

- ln -s /etc/nginx/sites-available/sfnewslovesnginx.com.conf /etc/nginx/sites-enabled/sfnewslovesnginx.com.conf
- ln -s /etc/nginx/sites-available/nginxmeanspower.com.conf /etc/nginx/sites-enabled/nginxmeanspower.com.conf

Next, create a sample html file named index.html inside /var/www/domain name>/public_html for each of the virtual hosts (replace domain name> as needed). Modify the following code as necessary:

!DOCTYPE html>
html>
  head>
    meta charset="utf-8">
    title>sfnews loves Nginx/title>
  /head>
  body>
  h1>sfnews loves Nginx!/h1>
  /body>
/html>

Finally, test the Nginx configuration and start the web server. If there are any errors in the configuration, you will be prompted to correct them:

- nginx -t && systemctl start nginx
Nginx Name-based and IP-based Virtual HostingCheck Nginx Configuration

Check Nginx Configuration

and add the following entries to your /etc/hosts file in your local machine as a basic name resolution strategy:

192.168.0.25 sfnewslovesnginx.com
192.168.0.25 nginxmeanspower.com

Then launch a web browser and go to the URLs listed above:

Nginx Name-based and IP-based Virtual HostingCheck Nginx Name Based Virtual Hosts

Check Nginx Name Based Virtual Hosts

To add more virtual hosts in Nginx, just repeat the steps outlined above as many times as needed.

​IP-based Virtual Hosts in Nginx

As opposed to name-based virtual hosts where all hosts are accessible through the same IP address, IP-based virtual hosts require a different IP:port combination each.

This allows the web server to return different sites depending on the IP address and port where the request is received on. Since named-based virtual hosts give us the advantage of sharing an IP address and port, they are the standard for general-purpose web servers and should be the setup of choice unless your installed version of Nginx does not support Server Name Indication (SNI), either because it is a REALLY outdated version, or because it was compiled without the –with-http_ssl_module compile option.

If,

- nginx -V

does not return the highlighted options below:

Nginx Name-based and IP-based Virtual HostingCheck Nginx Version and Modules

Check Nginx Version and Modules

you will need to update your version of Nginx or recompile it, depending on your original installation method. For compiling Nginx, follow below article:

  1. Install and Compile Nginx from Sources in RHEL/CentOS 7

Assuming we’re good to go, we need to note that another prerequisite for IP-based virtual hosts is the availability of separate IPs – either by assigning them to distinct network interfaces, or through the use of virtual IPs (also known as IP aliasing).

To perform IP aliasing in Debian (assuming you’re using eth0), edit /etc/network/interfaces as follows:

Debian and Derivatives

auto eth0:1
iface eth0:1 inet static
        address 192.168.0.25
        netmask 255.255.255.0
        network 192.168.0.0
        broadcast 192.168.0.255
        gateway 192.168.0.1
auto eth0:2
iface eth0:2 inet static
        address 192.168.0.26
        netmask 255.255.255.0
        network 192.168.0.0
        broadcast 192.168.0.255
        gateway 192.168.0.1

In the example above we create two virtual NICs out of eth0: eth0:1 (192.168.0.25) and eth0:2 (192.168.0.26).

CentOS and RHEL

In CentOS, rename /etc/sysconfig/network-scripts/ifcfg-enp0s3 as ifcfg-enp0s3:1 and make a copy as ifcfg-enp0s3:2, and then just change the following lines, respectively:

DEVICE="enp0s3:1"
IPADDR=192.168.0.25

and

DEVICE="enp0s3:2"
IPADDR=192.168.0.26

Once done, restart the network service:

- systemctl restart networking

Next, make the following changes to the server blocks previously defined in this article:

In /etc/nginx/sites-available/sfnewslovesnginx.com.conf:

listen 192.168.0.25:80

In /etc/nginx/sites-available/nginxmeanspower.com.conf:

listen 192.168.0.26:80

Finally, restart Nginx for the changes to take effect.

- systemctl restart nginx

and don’t forget to update your local /etc/hosts accordingly:

192.168.0.25 sfnewslovesnginx.com
192.168.0.26 nginxmeanspower.com

Thus, each request made to 192.168.0.25 and 192.168.0.26 on port 80 will return sfnewslovesnginx.com and nginxmeanspower.com, respectively:

Nginx Name-based and IP-based Virtual HostingCheck Nginx IP Based Virtual Host

Check Nginx IP Based Virtual Host

As you can see in the images above, you now have two IP-based virtual hosts using the only NIC in your server with two different IP aliases.

​ Summary

In this tutorial we have explained how to set up both name-based and IP-based virtual hosts in Nginx. Although you will probably want to use the first option, it’s important to know that the other option is still there if you need it – just make sure you take this decision after considering the facts outlined in this guide.

Additionally, you may want to bookmark the Nginx docs as it is worthy and well to refer to them often while creating server blocks (there you have it – we are talking in the Nginx language now) and configuring them. You won’t believe all of the options that are available to configure and tune this outstanding web server.

As always, don’t hesitate to drop us a line using the form below if you have any questions or comments about this article. We look forward to hearing from you, and your feedback about this guide is most welcome.

The Ultimate Guide to Secure, Harden and Improve Performance of Nginx Web Server

The Ultimate Guide to Secure, Harden and Improve Performance of Nginx Web Server &-8211; this Article or News was published on this date:2019-05-28 17:56:49 kindly share it with friends if you find it helpful

Nginx Security Hardening TipsNginx Security Hardening Tips

Nginx Security Hardening Tips

Based on the wonderful things you have heard about Nginx, perhaps you decided to give it a try. You may have liked it so much that are considering replacing your Apache installations with Nginx after going through some of the articles on the topic that we have published on this site.

If so, I’m sure you will welcome this guide with open arms since we are going to cover 12 tips to increase the security of your Nginx servers (ranging from keeping Nginx up to date all the way to using using TLS and redirecting HTTP to HTTPS), and you will note that some of them are very similar to what you would do with Apache.

Don’t Miss:

13 Apache Web Server Security and Hardening Tips

25 Apache Htaccess Tricks to Secure Apache Web Server

Nginx Testing Environment

We will use the following environment in this guide:

  1. Debian GNU/Linux 8.1 (jessie).
  2. IP address: 192.168.0.25 (sfnewslovesnginx.com) and 192.168.0.26 (nginxmeanspower.com), as described in the IP-based virtual hosts section at
    1. How to Setup Name-based and IP-based Virtual Hosts (Server Blocks) with Nginx
  3. Nginx version: nginx/1.6.2.
  4. For your convenience, here is the final configuration file (Pastebin link).

With that in mind, let’s begin.

​TIP -1: Keep Nginx up to date

At the time of this writing, the latest Nginx versions in the CentOS (in EPEL) and Debian repositories are 1.6.3 and 1.6.2-5, respectively.

Don’t Miss: Install Latest Stable Version of Nginx from Repositories and Source

Although installing software from the repositories is easier than compiling the program from source code, this last option has two advantages: 1) it allows you to build extra modules into Nginx (such as mod_security), and 2) it will always provide a newer version than the repositories (1.9.9 as of today). The release notes are always available in the Nginx web site.

Don’t Miss:

Protect Apache Against Brute Force and DDoS Attacks Using Mod_Security and Mod_Evasive

​TIP -2: Remove Unnecessary Modules in Nginx

To explicitly remove modules from Nginx while installing from source, do:

- ./configure --without-module1 --without-module2 --without-module3

For example:

- ./configure  --without-http_dav_module --withouthttp_spdy_module 

As you will probably guess, removing modules from a previous Nginx installation from source requires performing the compilation again.

A word of caution: Configuration directives are provided by modules. Make sure you don’t disable a module that contains a directive you will need down the road! You should check the nginx docs for the list of directives available in each module before taking a decision on disabling modules.

​TIP -3: Disable server_tokens Directive in Nginx

The server_tokens directive tells Nginx to display its current version on error pages. This is not desirable since you do not want to share that information with the world in order to prevent attacks at your web server caused by known vulnerabilities in that specific version.

To disable the server_tokens directive, set if to off inside a server block:

server {
    listen       192.168.0.25:80;
    Server_tokens        off;
    server_name  sfnewslovesnginx.com www.sfnewslovesnginx.com;
    access_log  /var/www/logs/sfnewslovesnginx.access.log;
    error_log  /var/www/logs/sfnewslovesnginx.error.log error;
        root   /var/www/sfnewslovesnginx.com/public_html;
        index  index.html index.htm;
}

Restart nginx and verify the changes:

Nginx Security Hardening TipsHide Nginx Version Information

Hide Nginx Version Information

​TIP -4: Deny HTTP User Agents in Nginx

A HTTP user agent is a software that is used for content negotiation against a web server. This also includes malware bots and crawlers that may end up impacting your web server’s performance by wasting system resources.

In order to more easily maintain the list of undesired user agents, create a file (/etc/nginx/blockuseragents.rules for example) with the following contents:

map $http_user_agent $blockedagent {
        default         0;
        ~*malicious     1;
        ~*bot           1;
        ~*backdoor      1;
        ~*crawler       1;
        ~*bandit        1;
}

Next, place the following line before the server block definition:

include /etc/nginx/blockuseragents.rules;

And an if statement to return a 403 response if the user agent string is in the black list defined above:

Nginx Security Hardening TipsDisable User Agents in Nginx

Disable User Agents in Nginx

Restart nginx, and all user agents whose string matches the above will be blocked from accessing your web server. Replace 192.168.0.25 with your server’s IP and feel free to choose a different string for the --user-agent switch of wget:

- wget http://192.168.0.25/index.html
- wget --user-agent "I am a bandit haha" http://192.168.0.25/index.html 
Nginx Security Hardening TipsBlock User Agents in Nginx

Block User Agents in Nginx

​TIP -5: Disable Unwanted HTTP Methods in Nginx

Also known as verbs, HTTP methods indicate the desired action to be taken on a resource served by Nginx. For common web sites and applications, you should only allow GET, POST, and HEAD and disable all others.

To do so, place the following lines inside a server block. A 444 HTTP response means an empty response and is often used in Nginx to fool malware attacks:

if ($request_method !~ ^(GET|HEAD|POST)$) {
   return 444;
}

To test, use curl to send a DELETE request and compare the output to when you send a regular GET:

- curl -X DELETE http://192.168.0.25/index.html
- curl -X POST http://192.168.0.25/index.html 
Nginx Security Hardening TipsDisable Unwanted HTTP Requests in Nginx

Disable Unwanted HTTP Requests in Nginx

​TIP -6: Set Buffer Size Limitations in Nginx

To prevent buffer overflow attacks against your Nginx web server, set the following directives in a separate file (create a new file named /etc/nginx/conf.d/buffer.conf, for example):

client_body_buffer_size  1k;
client_header_buffer_size 1k;
client_max_body_size 1k;
large_client_header_buffers 2 1k;

The directives above will ensure that requests made to your web server will not cause a buffer overflow in your system. Once again, refer to the docs for further details on what each of them does.

Then add an include directive in the configuration file:

include /etc/nginx/conf.d/*.conf;
Nginx Security Hardening TipsSet Buffer Size in Nginx

Set Buffer Size in Nginx

​TIP -7: Limit the Number of Connections by IP in Nginx

In order to limit the connections by IP, use the limit_conn_zone (in a http context or at least outside the server block) and limit_conn (in a http, server block, or location context) directives.

However, keep in mind that not all connections are counted – but only those that have a request processed by the server and its whole request header has been read.

For example, let’s set the maximum number of connections to 1 (yes, it’s an exaggeration, but it will do the job just fine in this case) in a zone named addr (you can set this to whatever name you wish):

limit_conn_zone $binary_remote_addr zone=addr:5m;
limit_conn addr 1;
Nginx Security Hardening TipsLimit Number of HTTP Requests in Nginx

Limit Number of HTTP Requests in Nginx

A simple test with Apache Benchmark (Perform Nginx Load) where 10 total connections are made with 2 simultaneous requests will help us to demonstrate our point:

- ab -n 10 -c 2 http://192.168.0.25/index.html

See the next tip for further details.

​TIP -8: Setup Monitor Logs for Nginx

Once you have performed the test described in the previous tip, check the error log that is defined for the server block:

Nginx Security Hardening TipsNginx Error Log

Nginx Error Log

You may want to use grep to filter the logs for failed requests made to the addr zone defined in TIP -7:

- grep addr /var/www/logs/sfnewslovesnginx.error.log --color=auto
Nginx Security Hardening TipsNginx Log Monitoring

Nginx Log Monitoring

Likewise, you can filter the access log for information of interest, such as:

  1. Client IP
  2. Browser type
  3. HTTP request type
  4. Resource requested
  5. Server block answering the request (useful if several virtual hosts are logging to the same file).

And take appropriate action if you detect any unusual or undesired activity.

​TIP -9: Prevent Image Hotlinking in Nginx

Image hotlinking happens when a person displays in another site an image hosted on yours. This causes an increase in your bandwidth use (which you pay for) while the other person happily displays the image as if it was his or her property. In other words, it’s a double loss for you.

For example, let’s say you have a subdirectory named img inside your server block where you store all the images used in that virtual host. To prevent other sites from using your images, you will need to insert the following location block inside your virtual host definition:

location /img/ {
  valid_referers none blocked 192.168.0.25;
   if ($invalid_referer) {
     return   403;
   }
}

Then modify the index.html file in each virtual host as follows:

192.168.0.26

192.168.0.25

!DOCTYPE html>
html>
head>
meta charset=”utf-8″>
title>Nginx means power/title>
/head>
body>
h1>Nginx means power!/h1>
img src=”http://192.168.0.25/img/nginx.png” />
/body>
/html>
!DOCTYPE html>
html>
head>
meta charset=”utf-8″>
title>sfnews loves Nginx/title>
/head>
body>
h1>sfnews loves Nginx!/h1>
img src=”img/nginx.png” />
/body>
/html>

Now browse to each site and as you can see, the image is correctly displayed in 192.168.0.25 but is replaced by a 403 response in 192.168.0.26:

Nginx Security Hardening TipsDisable Nginx Image Hotlinking

Disable Nginx Image Hotlinking

Note that this tip depends on the remote browser sending the Referer field.

​TIP -10: Disable SSL and only Enable TLS in Nginx

Whenever possible, do whatever it takes to avoid SSL in any of its versions and use TLS instead. The following ssl_protocols should be placed in a server or http context in your virtual host file or is a separate file via an include directive (some people use a file named ssl.conf, but it’s entirely up to you):

ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;

For example:

Nginx Security Hardening TipsDisable SSL and Enable TLS in Nginx

Disable SSL and Enable TLS in Nginx

​TIP -11: Create Certificates in Nginx

First off, generate a key and a certificate. Feel free to use a different type of encryption if you want:

- openssl genrsa -aes256 -out sfnewslovesnginx.key 1024
- openssl req -new -key sfnewslovesnginx.key -out sfnewslovesnginx.csr
- cp sfnewslovesnginx.key sfnewslovesnginx.key.org
- openssl rsa -in sfnewslovesnginx.key.org -out sfnewslovesnginx.key
- openssl x509 -req -days 365 -in sfnewslovesnginx.csr -signkey sfnewslovesnginx.key -out sfnewslovesnginx.crt

Then add the following lines inside a separate server block in preparation for the next tip (http --> https redirection) and move the SSL-related directives to the new block as well:

server {
    listen 192.168.0.25:443 ssl;
    server_tokens off;
    server_name  sfnewslovesnginx.com www.sfnewslovesnginx.com;
    root   /var/www/sfnewslovesnginx.com/public_html;
    ssl_certificate /etc/nginx/sites-enabled/certs/sfnewslovesnginx.crt;
    ssl_certificate_key /etc/nginx/sites-enabled/certs/sfnewslovesnginx.key;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
}

In the next tip we will verify how our site is now using a self-signed cert and TLS.

​TIP -12: Redirect HTTP traffic to HTTPS in Nginx

Add the following line to the first server block:

return 301 https://$server_name$request_uri;
Nginx Security Hardening TipsRedirect HTTP to HTTPS in Nginx

Redirect HTTP to HTTPS in Nginx

The above directive will return a 301 (Moved permanently) response, which is used for permanent URL redirection whenever a request is made to port 80 of your virtual host, and will redirect the request to the server block we added in the previous tip.

The image below shows the redirection and confirms the fact that we are using TLS 1.2 and AES-256 for encryption:

Nginx Security Hardening TipsVerify TLS Nginx Encryption

Verify TLS Nginx Encryption

Summary

In this article we have shared a few tips to secure your Nginx web server. We would love to hear what you think and, if you have other tips that you would like to share with the rest of the community, feel free to let us know by sending us a note using the comment form below.

How to Install Nginx 1.15, MariaDB 10 and PHP 7 on CentOS 7

How to Install Nginx 1.15, MariaDB 10 and PHP 7 on CentOS 7 &-8211; this Article or News was published on this date:2019-05-28 17:30:00 kindly share it with friends if you find it helpful

In this article we will explain how to install a LEMP stack (Linux, Nginx, MariaDB, PHP) along with PHP-FPM on RHEL/CentOS 7/6 and Fedora 26-29 servers using yum and dnf package manager.

During the process we will install and enable Epel, Remi, Nginx and MariaDB repositories in order to be able to install the latest versions of these packages.

Read Also: Install Apache, MySQL 8 or MariaDB 10 and PHP 7 on CentOS 7

Step 1: Installing EPEL and Remi Repository

EPEL (Extra Packages for Enterprise Linux) is a community based repository offers add-on software packages for RHEL-based Linux distributions.

Remi is a repository where you can find the latest versions of the PHP stack (full featured) for installation in the Fedora and Enterprise Linux distributions.

On RHEL/CentOS 7

- yum update && yum install epel-release
- rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-7.rpm

------ For RHEL 7 Only ------
- subscription-manager repos --enable=rhel-7-server-optional-rpms

On RHEL/CentOS 6

- yum update && yum install epel-release
- rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm

------ For RHEL 6 Only ------
- subscription-manager repos --enable=rhel-6-server-optional-rpms

On Fedora 24-29

- rpm -Uvh http://rpms.remirepo.net/fedora/remi-release-29.rpm  [On Fedora 29]
- rpm -Uvh http://rpms.remirepo.net/fedora/remi-release-28.rpm  [On Fedora 28]
- rpm -Uvh http://rpms.remirepo.net/fedora/remi-release-27.rpm  [On Fedora 27]
- rpm -Uvh http://rpms.remirepo.net/fedora/remi-release-26.rpm  [On Fedora 26]
- rpm -Uvh http://rpms.remirepo.net/fedora/remi-release-25.rpm  [On Fedora 25]
- rpm -Uvh http://rpms.remirepo.net/fedora/remi-release-24.rpm  [On Fedora 24]

Step 2: Installing Nginx and MariaDB Repositories

The Nginx repository is only needed in RHEL and CentOS distributions. Create a file called /etc/yum.repos.d/nginx.repo and add the following lines to it.

For RHEL 7/6:

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

For CentOS 7/6:

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

To enable the MariaDB repository, create a file named /etc/yum.repos.d/mariadb.repo with the following contents:

[mariadb] 
name = MariaDB 
baseurl = http://yum.mariadb.org/10.1/centos7-amd64 
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB 
gpgcheck=1 

Step 4: Installing Ngnix and MariaDB

Nginx (Engine X) is open source, robust, lightweight and high performance Web server, reverse proxy sever and also mail proxy server for HTTP, SMTP, POP3 and IMAP protocols. For further details, visit http://wiki.nginx.org/Overview.

MariaDB is a fork of the well-known MySQL, one of the world’s most popular Relational Database Management System (RDBMS). It is entirely developed by the community and as such it is intended to remain FOSS and compatible with the GPL.

To install Ngnix and MariaDB, run the following commands.

----------- Installing on RHEL/CentOS 7/6 ----------- 
- yum --enablerepo=remi install nginx MariaDB-client MariaDB-server php php-common php-fpm 

----------- Installing on Fedora ----------- 
- dnf --enablerepo=remi install nginx MariaDB-client MariaDB-server php php-common php-fpm 

Step 3: Installing PHP Using Remi Repository

PHP (Hypertext Preprocessor) is a Free and Open Source server-side scripting language that is best suited for web development. It can be used to produce dynamic web pages for a website and is most frequently found in *nix servers. One of the advantages of PHP is that it is easily extensible through the use of a wide variety of modules.

To install PHP, first you need to enable Remi repository by installing yum-utils, a collection of useful programs for managing yum repositories and packages.

- yum install yum-utils

Once installed, you can use yum-config-manager provided by yum-utils to enable Remi repository as the default repository for installing different PHP versions as shown.

For example, to install PHP 7.x version, use the following command.

------------- On CentOS & RHEL ------------- 
- yum-config-manager --enable remi-php70 && yum install php       [Install PHP 7.0]
- yum-config-manager --enable remi-php71 && yum install php       [Install PHP 7.1]
- yum-config-manager --enable remi-php72 && yum install php       [Install PHP 7.2]
- yum-config-manager --enable remi-php73 && yum install php       [Install PHP 7.3]

------------- On Fedora ------------- 
- dnf --enablerepo=remi install php70      [Install PHP 7.0]
- dnf --enablerepo=remi install php71      [Install PHP 7.1]
- dnf --enablerepo=remi install php72      [Install PHP 7.2]
- dnf --enablerepo=remi install php73      [Install PHP 7.3]

Next, we are going to install all these following PHP modules.

------ On RHEL/CentOS 7/6 ------
- yum --enablerepo=remi install php-mysqlnd php-pgsql php-fpm php-pecl-mongo php-pdo php-pecl-memcache php-pecl-memcached php-gd php-xml php-mbstring php-mcrypt php-pecl-apcu php-cli php-pear

------ On Fedora ------
- dnf --enablerepo=remi install php-mysqlnd php-pgsql php-fpm php-pecl-mongo php-pdo php-pecl-memcache php-pecl-memcached php-gd php-xml php-mbstring php-mcrypt php-pecl-apcu php-cli php-pear

Step 6: Stopping and Disabling Apache Service

By default, Apache and Nginx listen in same port (TCP 80). For that reason, if Apache is installed in your server, you need to stop it and disable / mask it (a stronger version of disable that links the service to /dev/null) in order to use Nginx, or you can remove it if you’re not planning on using it anymore.

- systemctl stop httpd 
- systemctl disable httpd 
or 
- systemctl mask httpd 

Step 7: Starting/Stopping Nginx, MariaDB and PHP-FPM

----------- Enable Nginx, MariaDB and PHP-FPM on Boot ----------- 
- systemctl enable nginx 
- systemctl enable mariadb 
- systemctl enable php-fpm 
 
----------- Start Nginx, MariaDB and PHP-FPM ----------- 
- systemctl start nginx 
- systemctl start mariadb 
- systemctl start php-fpm 

Step 8: Configuring Nginx and PHP-FPM

Let us now create a directory structure for your website (a virtual host, or server block as it is called in Nginx) under /srv/www/. In this example we will use www.sfnews.com, but feel free to choose another domain and main directory if you want.

- mkdir -p /srv/www/sfnews/public_html 
- mkdir /srv/www/sfnews/logs 
- chown -R nginx:nginx /srv/www/sfnews  

Step 9: Configuring Nginx Virtual Host Directories

As you know, the ability of running several sites from the same machine is one of the distinguishing features of major web servers. Let us now proceed to create the directories to store our server blocks (known as virtual hosts in Apache) under /etc/nginx.

- mkdir /etc/nginx/sites-available 
- mkdir /etc/nginx/sites-enabled 

The following line of code, which must be inserted before closing the http block in /etc/nginx/nginx.conf, will ensure that configuration files inside the /etc/nginx/sites-enabled directory will be taken into account when Nginx is running:

-- Load virtual host conf files. -- 
include /etc/nginx/sites-enabled/*; 
Configuring Nginx VirtualHostConfiguring Nginx VirtualHost

Configuring Nginx VirtualHost

To create the server block for sfnews.com, add the following lines of code to /etc/nginx/sites-available/sfnews (this file will be created when you enter the full path to start your preferred text editor). This is a basic virtual host config file.

server { 
	listen 80 default; 
	server_name sfnews; 
	access_log /srv/www/sfnews/logs/access.log; 
	error_log /srv/www/sfnews/logs/error.log; 
	root /srv/www/sfnews/public_html; 
	location ~* .php$ { 
	fastcgi_index   index.php; 
	fastcgi_pass    127.0.0.1:9000; 
	include         fastcgi_params; 
	fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name; 
	fastcgi_param   SCRIPT_NAME        $fastcgi_script_name; 
	} 
} 

The process of “activating” a virtual host consists of creating a symbolic link from the definition of the sfnews virtual host to /etc/nginx/sites-enabled.

- ln -s /etc/nginx/sites-available/sfnews /etc/nginx/sites-enabled/sfnews 

In order to actually apply the changes we have been doing, we now need to restart Nginx. It is sometimes useful to check the configuration files for syntax errors before doing so:

- nginx -t 
- systemctl restart nginx 
- systemctl status nginx 
Configuring Nginx VirtualHostRestart Nginx and Verify Status

Restart Nginx and Verify Status

To access your newly created virtual host, you need to add the following line to /etc/hosts as a basic method of domain name resolution.

192.168.0.18	www.sfnews.com sfnews.com 

Step 10: Testing Nginx, MySQL, PHP and PHP-FPM

Let’s stick with the classic way of testing PHP. Create a file called test.php under /srv/www/sfnews/public_html/ and add the following lines of code to it.

The phpinfo() function shows a great deal of information about the current PHP installation:

?php 
	phpinfo(); 
?> 

Now point your web browser to http://sfnews/test.php and check the presence of the installed modules and additional software:

Congratulations! You now have a working installation of a LEMP stack. If something did not go as expected, feel free to contact us using the form below. Questions and suggestions are also welcome.

Learn How to Speed Up Websites Using Nginx and Gzip Module

Learn How to Speed Up Websites Using Nginx and Gzip Module &-8211; this Article or News was published on this date:2019-05-28 17:13:50 kindly share it with friends if you find it helpful

Even in a time when significant Internet speeds are available throughout the globe, every effort to optimize website load times is welcome with open arms.

In this article we will discuss a method to increase transfer speeds by reducing the file sizes through compression. This approach brings an extra benefit in that it also reduces the amount of bandwidth used in the process, and makes it cheaper for the website owner who pays for it.

To accomplish the goal stated in the above paragraph, we will use Nginx and its built-in gzip module in this article. As the official documentation states, this module is a filter that compresses responses using the well-known gzip compression method. This ensures that the size of the transmitted data will be compressed by half or even more.

Suggested Read: The Ultimate Guide to Secure, Harden and Boost Performance of Nginx Websites

By the time you reach the bottom of this post, you will have yet another reason to consider using Nginx to serve your websites and applications.

Installing Nginx Web Server

Nginx is available for all major modern distributions. Although we will use a CentOS 7 virtual machine (IP 192.168.0.29) for this article.

The instructions provided below will work with little (if any) modifications in other distributions as well. It is assumed that your VM is a fresh install; otherwise, you will have to make sure that there are not any other web servers (such as Apache) running on your machine.

To install Nginx along with its required dependencies, use the following command:

----------- On CentOS/RHEL 7 and Fedora 22-24 ----------- 
- yum update && yum install nginx

----------- On Debian and Ubuntu Distributions ----------- 
- apt update && apt install nginx

To verify that the installation has completed successfully and that Nginx can serve files, start the web server:

- systemctl start nginx
- systemctl enable nginx

and then open a web browser and go to http://192.168.0.29 (don’t forget to replace 192.168.0.29 with the IP address or hostname of your server). You should see the Welcome page:

Nginx Default Welcome PageNginx Default Welcome Page

Nginx Default Welcome Page

We must keep in mind that some file types can be compressed better than others. Plain text files (such as HTML, CSS, and JavaScript files) compress very well while others (.iso files, tarballs, and images, to name a few) do not, as they are already compressed by nature.

Thus, it is to be expected that the combination of Nginx and gzip will allow us to increase the transfer speeds of the former, while the latter may show little or no improvement at all.

It is also important to keep in mind that when the gzip module is enabled, HTML files are ALWAYS compressed, but other file types commonly found in websites and applications (namely, CSS and JavaScript) aren’t.

Testing Nginx Website Speeds WITHOUT the gzip Module

To begin, let’s download a complete Bootstrap template, a great combination of HTML, CSS, and JavaScript files.

After downloading the compressed file, we will unzip it to the root directory of our server block (remember that this is the Nginx equivalent of the DocumentRoot directive in an Apache virtual host declaration):

- cd /var/www/html
- wget https://github.com/BlackrockDigital/startbootstrap-creative/archive/gh-pages.zip
- unzip -a gh-pages.zip
- mv startbootstrap-creative-gh-pages sfnews

You should have the following directory structure inside /var/www/html/sfnews:

- ls -l /var/www/html/sfnews
Nginx Default Welcome PageNginx DocumentRoot Content

Nginx DocumentRoot Content

Now go to http://192.168.0.29/sfnews and make sure the page loads correctly. Most modern browser include a set of developer tools. In Firefox, you can open it via the Tools → Web Developer menu.

We are particularly interested in the Network submenu, which will allow us to monitor all network requests going on between our computer and the local network and the Internet.

Suggested Read: Install Mod_Pagespeed to Speed Up Nginx Performance Upto 10x

A shortcut to opening the Network menu in the developer tools is Ctrl + Shift + Q. Press that key combination or use the menu bar to open it.

Since we are interested in examining the transfer of HTML, CSS, and JavaScript files, click on the buttons in the bottom and refresh the page. In the main screen you will see the detail of the transfer of all the HTML, CSS, and JavaScript files:

Nginx Default Welcome PageCheck Nginx Uses Compression

Check Nginx Uses Compression

To the right of the Size column (which shows the individual file sizes) you’ll see the individual transfer timings. You can also double click on any given file to see more details in the Timings tab.

Make sure you take notes of the timings shown in the above image so that you can compare them with the same transfer once we have enabled the gzip module.

Enabling and Configuring the gzip Module in Nginx

To enable and configure the gzip module, open /etc/nginx/nginx.conf, locate the main server block as shown in the below image, and add or modify the following lines (don’t forget the semicolon at the end or Nginx will return an error message while restarting later!)

root     	/var/www/html;
gzip on;
gzip_types text/plain image/jpeg image/png text/css text/javascript;
Nginx Default Welcome PageEnable Gzip Module in Nginx

Enable Gzip Module in Nginx

The gzip directive turns on or off the gzip module, whereas gzip_types is used to list all the MIME types the module should handle.

To learn more about MIME types and view the available types, go to Basics_of_HTTP_MIME_types.

Testing Nginx Website Speeds With Gzip Compression Module

Once we have completed the above steps, let’s restart Nginx and reload the page by pressing Ctrl + F5 (again, this works in Firefox, so if you’re using a different browser consult first the corresponding documentation) to override the cache and let’s observe the transfer times:

- systemctl restart nginx

The network requests tab shows some significant improvements. Compare the timings to see for yourself, keeping in mind that it’s the transfers between our computer and 192.168.0.29 (transfers between Google servers and CDNs are beyond our grasp):

Nginx Default Welcome PageTesting and Verifying Nginx Gzip Compression

Testing and Verifying Nginx Gzip Compression

For example, let’s consider the following file transfer examples before / after enabling gzip. Timings are given in milliseconds:

  1. index.html (represented by /sfnews/ at the top of the list): 15 / 4
  2. Creative.min.css: 18 / 8
  3. jquery.min.js: 17 / 7

Doesn’t this make you love Nginx even more? As far as I’m concerned, it does!

Suggested Read: 5 Tips to Boost the Performance of Your Apache Web Server

Summary

In this article we have demonstrated that you can use the Nginx gzip module to speed up file transfers. The official documentation for gzip module lists other configuration directives that you may want to take a look at.

Additionally, the Mozilla Developer Network website has an entry about the Network Monitor that explains how to use this tool to understand what’s going on behind the scenes in a network request.

As always, feel free to use the comment form below if you have any questions about this article. We are always looking forward to hearing from you!