Install Nginx with ngx_pagespeed on CentOS 7

Install Nginx with ngx_pagespeed on CentOS 7

Scan your Web-Server for Malware with ISPProtect now. Get Free Trial.

Ngx-pagespeed is a free and open source Nginx module that can be used to speeds up your site and reduces page load time. It works by automatically applying web performance best practices to pages and associated assets without requiring you to modify your existing content or workflow. You can easily optimize various files such as CSS, HTML, png, and jpg using Ngx-pagespeed module.

Ngx-pagespeed comes with lots of features, some of them are listed below:

  • Supports image dynamic resizing, recompression and optimization.
  • Small resource inlining.
  • HTML rewriting.
  • Cache lifetime extension.
  • Deferring JavaScript and Image loading.

In this tutorial, we will discuss how to compile Nginx with ngx_pagespeed module on CentOS 7 server.

Requirements

  • Fresh CentOS 7 server installed on your system.
  • Sudo user with root privileges.

1 Update the System

Let’s start by updating your system to the latest stable version. You can do this by running the following command:

sudo yum update -y

Once your system is updated, restart the system and login with sudo user.

2 Install Required Dependencies

You will need to install some packages in order to compile Nginx. You can install all these dependencies by running the following command:

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

Once all the required dependencies are installed, you can proceed to the next step.

3 Compile Nginx with Ngx-pagespeed

To install Nginx with ngx-pagespeed module you will need to compile Nginx from source. First, you will need to download the Nginx source. You can download it by running the following command:

wget http://nginx.org/download/nginx-1.12.0.tar.gz

To compile Nginx with ngx_pagespeed module, you will also need to download ngx_pagespeed source package. You can download it with the following command:

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

Once both packages are download, Extract them with the following command:

tar -xvzf nginx-1.12.0.tar.gz
tar -xvzf v1.12.34.2-stable.zip

Next, you will also need to download the PageSpeed optimization libraries to compile Nginx. You can download it with the following command:

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

Now, let’s start to compile Nginx with the pagespeed module.

First, change the directory to the Nginx source directory with the following command:

cd nginx-1.12.0

Next, configure the Nginx source with the following command:

sudo ./configure –add-module=$HOME/ngx_pagespeed-1.12.34.2-stable –user=nobody –group=nobody –pid-path=/var/run/nginx.pid ${PS_NGX_EXTRA_FLAGS}

Once the configuration is completed, compile Nginx by running the following command:

sudo make

The above command will take several minutes. After that you can install nginx by running the following command:

sudo make install

Once Nginx is installed, you will need to create a symlink for the Nginx:

sudo ln -s /usr/local/nginx/conf/ /etc/nginx
sudo ln -s /usr/local/nginx/sbin/nginx /usr/sbin/nginx

4 Create Nginx Startup Script

You will also need to create a startup script for Nginx to stop and start Nginx. You can do this by creating nginx file inside /etc/init.d directory:

sudo nano /etc/init.d/nginx

Add the following lines:

#!/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
# config:      /etc/sysconfig/nginx
# pidfile:     /var/run/nginx.pid

# 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"

[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx

lockfile=/var/lock/subsys/nginx

make_dirs() {
   # make required directories
   user=`$nginx -V 2>&1 | grep "configure arguments:.*--user=" | sed 's/[^*]*--user=([^ ]*).*/1/g' -`
   if [ -n "$user" ]; then
      if [ -z "`grep $user /etc/passwd`" ]; then
         useradd -M -s /bin/nologin $user
      fi
      options=`$nginx -V 2>&1 | grep 'configure arguments:'`
      for opt in $options; do
          if [ `echo $opt | grep '.*-temp-path'` ]; then
              value=`echo $opt | cut -d "=" -f 2`
              if [ ! -d "$value" ]; then
                  # echo "creating" $value
                  mkdir -p $value && chown -R $user $value
              fi
          fi
       done
    fi
}

start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    make_dirs
    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
    sleep 1
    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

Save and close the file when you are finished, then give execution permission to it:

sudo chmod +x /etc/init.d/nginx

Now start nginx service and enable it to start on boot time with the following command:

sudo systemctl start nginx
sudo systemctl enable nginx

Once you are done, you can proceed to the next step.

5 Configure Nginx

Now, Nginx is installed with ngx-pagespeed support. By default PageSpeed is disabled. Before enable it, it is recommended to test your website speed. Next, you will need to create a cache directory for ngx-pagespeed and also assign ownership for it to Nginx:

sudo mkdir -p /var/ngx_pagespeed_cache
sudo chown -R nobody:nobody /var/ngx_pagespeed_cache

Next, you will need to make some changes in /etc/nginx/nginx.conf file. You can do this by running the following command:

sudo nano /etc/nginx/nginx.conf

Add the following code between the server block:

# Pagespeed main settings

pagespeed on;
pagespeed FileCachePath /var/ngx_pagespeed_cache;

# Ensure requests for pagespeed optimized resources go to the pagespeed
# handler and no extraneous headers get set.

location ~ ".pagespeed.([a-z].)?[a-z]{2}.[^.]{10}.[^.]+" { add_header "" ""; }
location ~ "^/ngx_pagespeed_static/" { }
location ~ "^/ngx_pagespeed_beacon" { }

Note: If you are using virtual hosting then add the above pagespeed directives to each server block config file to enable pagespeed on each website.

Save and close the file when you are finished, then check the Nginx for any configuration error with the following command:

sudo nginx -t

If everything is fine, you should see the following output:

nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

Finally, restart Nginx for the changes to take effect:

sudo systemctl restart nginx

Once Nginx is configured, you can proceed to test Ngx-pagespeed.

6 Test Ngx-pagespeed

Nginx is now up and running. It’s time to check whether the module is working or not. You can check it by running the following command:

curl -I -p http://localhost

You should see the following output:

HTTP/1.1 200 OK
Server: nginx/1.12.0
Content-Type: text/html
Connection: keep-alive
Vary: Accept-Encoding
Date: Wed, 21 Jun 2017 17:21:08 GMT
X-Page-Speed: 1.12.34.2-0
Cache-Control: max-age=0, no-cache

You should see X-Page-Speed and it’s version number in the above output. This means that you have successfully installed Ngx_pagespeed on your server.

Conclusion

Congratulations! you have successfully installed Nginx with Ngx-pagespeed module support. I hope you can now easily deploy it in a production environment. Feel free to comments me if you have any questions.

Source