Advanced web server setup (Apache2 + Nginx)

In this guide, we will consider the procedure for installing and configuring the operation of two web servers in order to take advantage of each of them; the guide implies both separate configuration and mutual.



This article will talk about setting up a server using: Apache2, Nginx, ngx_pagespeed, PHP, PHP-FPM, MariaDB and MemCached .



Nginx



HTTP server and reverse proxy, mail proxy, and general purpose TCP / UDP proxy.



Installation



Install the packages required to connect the apt repository:



sudo apt install curl gnupg2 ca-certificates lsb-release


To connect the apt repository for the stable version of nginx, run the following command:



echo "deb http://nginx.org/packages/debian `lsb_release -cs` nginx" \
    | sudo tee /etc/apt/sources.list.d/nginx.list


Now you need to import the official key used by apt to authenticate packages:



curl -fsSL https://nginx.org/keys/nginx_signing.key | sudo apt-key add -


Check if the correct key was imported:



sudo apt-key fingerprint ABF5BD827BD9BF62


The command output should contain the complete key fingerprint 573B FD6B 3D8F BC64 1079 A6AB ABF5 BD82 7BD9 BF62:



pub   rsa2048 2011-08-19 [SC] [expires: 2024-06-14]
      573B FD6B 3D8F BC64 1079  A6AB ABF5 BD82 7BD9 BF62
uid   [ unknown] nginx signing key


To install nginx, run the following commands:



sudo apt update && sudo apt install nginx


Customization



Launch nginx



systemctl enable nginx && systemctl start nginx


Check that the user nginx user www-data:



vi /etc/nginx/nginx.conf


-. http://«IP- ».



«Welcome to nginx!».



PHP-FPM



FastCGI — - . FPM Fastcgi Process Manager.





PHP-FPM:



apt-get install php-fpm




php-fpm :



systemctl enable php7.3-fpm && systemctl start php7.3-fpm


, php-fpm 7.2. — php php -v.



ngx_pagespeed



ngx_pagespeed ( pagespeed) – Nginx, . .





:



sudo apt-get install unzip gcc make g++ libpcre3-dev zlib1g-dev build-essential libpcre3 uuid-dev




, ngx_pagespeed:



mkdir /etc/nginx/build
cd /etc/nginx/build


nginx:



nginx -v


:



wget -qO - http://nginx.org/download/nginx-1.18.0.tar.gz | tar zxfv -


nginx 1.18



ngx_pagespeed:



git clone https://github.com/pagespeed/ngx_pagespeed.git

cd ngx_pagespeed/

git checkout tags/latest-stable

cat PSOL_BINARY_URL


psol:



psol_url=https://dl.google.com/dl/page-speed/psol/${NPS_VERSION}.tar.gz [ -e scripts/format_binary_url.sh ] && psol_url=$(scripts/format_binary_url.sh PSOL_BINARY_URL)

wget ${psol_url}
tar zxf 1.13.35.2-x64.tar.gz


ngx_pagespeed.so:



cd ../nginx-1.18.0/

./configure --add-dynamic-module=../ngx_pagespeed --with-compat

make

ls objs/*so


ngx_pagespeed.so:



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


Apache2



.htaccess, , - Apache.





apache php:



apt-get install apache2 libapache2-mod-php




:



vi /etc/apache2/ports.conf


:



Listen 127.0.0.1:8080

# <IfModule ssl_module>
#    Listen 443
# </IfModule>

# <IfModule mod_gnutls.c>
#    Listen 443
# </IfModule>


8080, 80 NGINX. 443, NGINX.



mpm_event:



a2dismod mpm_event


, apache2 mpm_event. php 7 .



mpm_prefork:



a2enmod mpm_prefork


php:



a2enmod php7.3


rewrite:



a2enmod rewrite


setenvif:



a2enmod setenvif


:



systemctl enable apache2 && systemctl start apache2


http://«IP- »:8080. .



Server API Apache.



Apache2 Real IP



apache NGINX, IP- 127.0.0.1. , , . remoteip.





:



vi /etc/apache2/mods-available/remoteip.conf




:



<IfModule remoteip_module>
  RemoteIPHeader X-Forwarded-For
  RemoteIPTrustedProxy 127.0.0.1/8
</IfModule>


:



a2enmod remoteip


apache:



systemctl restart apache2


http://«IP- », phpinfo.



Apache Environment , REMOTE_ADDR.



PHP



PHP PHP-FPM:



apt install php-xml php-intl php-gd php-curl php-zip php-mbstring php-bcmath php-bz2 php-cgi php-cli php-common php-dba php-dev php-enchant php-gmp php-imap php-interbase php-json php-ldap php-odbc php-opcache php-phpdbg php-pspell php-readline php-recode php-sybase php-tidy php-xmlrpc php-xsl


Mysql (Mariadb)





MariaDB:



apt-get install mariadb-server php-mysql php-mysqli




:



systemctl enable mariadb
systemctl start mariadb


root:



mysqladmin -u root password


apache2:



systemctl restart apache2


:



mysql -uroot -p

mysql> GRANT ALL PRIVILEGES ON *.* TO 'dbuser'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION;

# ALL PRIVILEGES:      .
# *.* :        .
# dbuser -   .
# localhost -          .
# password - ,    .
# WITH GRANT OPTION -      .


adminer.php



> update user set plugin='' where User='root';

> flush privileges;

> exit


:



sudo systemctl restart mariadb.service


Memcached



Memcached — , -.





, :



apt-get install memcached php-memcached




:



systemctl enable memcached && systemctl start memcached


apache2:



systemctl restart apache2


, memcached PHP, — phpinfo Memcached.



memcached.conf:



vi /etc/memcached.conf


:



netstat -tap | grep memcached




:



adduser dev


www-data:



adduser dev www-data


sudo :



usermod -aG sudo dev






:



mkdir -p /var/www/example.com/{www,tmp}
mkdir -p /var/www/example.com/log/{nginx,apache}


:



chown -R www-data:www-data /var/www/example.com/www
chmod -R 775 /var/www/example.com/www


:



vi /var/www/example.com/www/index.php


:



<?php phpinfo(); ?>




Nginx http



server {
    listen       80;
    server_name  example.com;
    set $root_path /var/www/example.com/www;

    access_log /var/www/example.com/log/nginx/access_log;
    error_log /var/www/example.com/log/nginx/error_log;

    root   $root_path;

    gzip  on;
    gzip_disable "msie6";
    gzip_min_length 1000;
    gzip_vary on;
    gzip_proxied    expired no-cache no-store private auth;
    gzip_types      text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss;

    location / {
        location ~ [^/]\.ph(p\d*|tml)$ {
            try_files /does_not_exists @fallback;
        }

        location ~* ^.+\.(jpg|jpeg|gif|png|css|zip|tgz|gz|rar|bz2|doc|docx|xls|xlsx|exe|pdf|ppt|tar|wav|bmp|rtf|js)$ {
            try_files $uri $uri/ @fallback;
        }

        location ~* \.(?:css(\.map)?|js(\.map)?|jpe?g|png|gif|ico|cur|heic|webp|tiff?|mp3|m4a|aac|ogg|midi?|wav|mp4|mov|webm|mpe?g|avi|ogv|flv|wmv)$ {
            expires 7d;
            access_log off;
        }

        location ~* \.(?:svgz?|ttf|ttc|otf|eot|woff2?)$ {
            add_header Access-Control-Allow-Origin "*";
            expires 7d;
            access_log off;
        }

        location = /favicon.ico {
            log_not_found off;
            access_log off;
        }

        location = /robots.txt {
            log_not_found off;
            access_log off;
        }

        location / {
            try_files /does_not_exists @fallback;
        }
    }

    #   PHP
    location @fallback {
        proxy_pass http://127.0.0.1:8080;
        proxy_redirect http://127.0.0.1:8080 /;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        access_log off;
    }

    #   PHP-FPM
    location @fallback {
        index index.php index.html index.htm; 
        fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $root_path$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_param DOCUMENT_ROOT $root_path;
    }
}


:



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


8080, apache, (jpg, png, css ).



apache2



:



vi /etc/apache2/sites-available/example.com.conf


<VirtualHost 127.0.0.1:8080>
    Define root_domain example.com
    Define root_path /var/www/example.com

    ServerName ${root_domain}
    ServerAlias www.${root_domain}
    DocumentRoot ${root_path}/www

    ErrorLog ${root_path}/log/apache/error_log
    TransferLog  ${root_path}/log/apache/access_log

    <IfModule mod_dir.c>
        DirectoryIndex index.php index.html index.htm
    </IfModule>

    <Directory /var/www/example.com/www>
        AllowOverride All
        Options Indexes ExecCGI FollowSymLinks
        Require all granted
    </Directory>

    <IfModule setenvif_module>
        SetEnvIf X-Forwarded-Proto https HTTPS=on
    </IfModule>

    <IfModule php7_module>
        php_admin_value upload_tmp_dir ${root_path}/tmp
        php_admin_value doc_root ${root_path}
        php_value open_basedir    ${root_path}:/usr/local/share/smarty:/usr/local/share/pear
        php_value post_max_size 512M
        php_value upload_max_filesize 512M
        php_flag short_open_tag On
    </IfModule>
</VirtualHost>


:



ln -s /etc/apache2/sites-available/example.com.conf /etc/apache2/sites-enabled/example.com.conf




:



nginx -t
apachectl configtest


-:



systemctl reload nginx
systemctl reload apache2


https ( )



:



vi /etc/nginx/conf.d/example.com.conf


#     ,     ip   .
server {
    listen 80;
    server_name _ip;
    return 301 https://example.com$request_uri;
}

server {
    listen       443 ssl;
    ssl on;
    ssl_certificate /etc/nginx/ssl/cert.pem;
    ssl_certificate_key /etc/nginx/ssl/cert.key;

    server_name example.com;
    set $root_path /var/www/example.com/www;

    access_log /var/www/example.com/log/nginx/access_log;
    error_log /var/www/example.com/log/nginx/error_log;
    gzip  on;
    gzip_disable "msie6";
    gzip_min_length 1000;
    gzip_vary on;
    gzip_proxied    expired no-cache no-store private auth;
    gzip_types      text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss

    root   $root_path;

    location / {
        location ~ [^/]\.ph(p\d*|tml)$ {
            try_files /does_not_exists @fallback;
        }

        location ~* ^.+\.(jpg|jpeg|gif|png|css|zip|tgz|gz|rar|bz2|doc|docx|xls|xlsx|exe|pdf|ppt|tar|wav|bmp|rtf|js)$ {
            try_files $uri $uri/ @fallback;
        }

        location ~* \.(?:css(\.map)?|js(\.map)?|jpe?g|png|gif|ico|cur|heic|webp|tiff?|mp3|m4a|aac|ogg|midi?|wav|mp4|mov|webm|mpe?g|avi|ogv|flv|wmv)$ {
            expires 7d;
            access_log off;
        }

        location ~* \.(?:svgz?|ttf|ttc|otf|eot|woff2?)$ {
            add_header Access-Control-Allow-Origin "*";
            expires 7d;
            access_log off;
        }

        location = /favicon.ico {
            log_not_found off;
            access_log off;
        }

        location = /robots.txt {
            log_not_found off;
            access_log off;
        }

        location / {
            try_files /does_not_exists @fallback;
        }
    }

    #   PHP
    location @fallback {
        proxy_pass http://127.0.0.1:8080;
        proxy_redirect http://127.0.0.1:8080 /;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        access_log off;
    }

    #   PHP-FPM
    location @fallback {
        index index.php index.html index.htm; 
        fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $root_path$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_param DOCUMENT_ROOT $root_path;
    }
}


8080, apache, (jpg, png, css ).



Apache2



:



vi /etc/apache2/sites-available/example.com.conf


<VirtualHost 127.0.0.1:8080>
    Define root_domain example.com
    Define root_path /var/www/example.com

    ServerName ${root_domain}
    ServerAlias www.${root_domain}
    DocumentRoot ${root_path}/www

    ErrorLog ${root_path}/log/apache/error_log
    TransferLog  ${root_path}/log/apache/access_log

    <IfModule mod_dir.c>
        DirectoryIndex index.php index.html index.htm
    </IfModule>

    <Directory /var/www/example.com/www>
        AllowOverride All
        Options Indexes ExecCGI FollowSymLinks
        Require all granted
    </Directory>

    <IfModule setenvif_module>
        SetEnvIf X-Forwarded-Proto https HTTPS=on
    </IfModule>

    <IfModule php7_module>
        php_admin_value upload_tmp_dir ${root_path}/tmp
        php_admin_value doc_root ${root_path}
        php_value open_basedir    ${root_path}:/usr/local/share/smarty:/usr/local/share/pear
        php_value post_max_size 512M
        php_value upload_max_filesize 512M
        php_flag short_open_tag On
    </IfModule>
</VirtualHost>


:



ln -s /etc/apache2/sites-available/example.com.conf /etc/apache2/sites-enabled/example.com.conf




:



nginx -t
apachectl configtest


-:



systemctl reload nginx
systemctl reload apache2


ngx_pagespeed on



PageSpeed



Open the file nginx.conf:



vi /etc/nginx/nginx.conf


Add to the beginning:



load_module modules/ngx_pagespeed.so;


PageSpeed ​​is httpconfigured in context, so put these directives in a new configuration file called under the directory example.com.confin the file /etc/nginx/conf.d.



#   
pagespeed MessageBufferSize 10240;
#    
pagespeed FileCachePath /var/cache/nginx_pagespeed;

server {
    listen       80;
    server_name example.com;
    set $root_path /var/www/example.com/www;

    #  pagespeed
    pagespeed on;

    root   $root_path;

    #    
    pagespeed LoadFromFile "http://www.example.com" "/var/www/example.com/www";

    access_log /var/www/example.com/log/nginx/access_log;
    error_log /var/www/example.com/log/nginx/error_log;

    #  
    pagespeed RewriteLevel CoreFilters;
    pagespeed EnableFilters collapse_whitespace,remove_comments;
    pagespeed DisableFilters rewrite_images;

    gzip  on;
    gzip_disable "msie6";
    gzip_min_length 1000;
    gzip_vary on;
    gzip_proxied    expired no-cache no-store private auth;
    gzip_types      text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss;

    location / {
        location ~ [^/]\.ph(p\d*|tml)$ {
            try_files /does_not_exists @fallback;
        }

        location ~* ^.+\.(jpg|jpeg|gif|png|css|zip|tgz|gz|rar|bz2|doc|docx|xls|xlsx|exe|pdf|ppt|tar|wav|bmp|rtf|js)$ {
            try_files $uri $uri/ @fallback;
        }

        location ~* \.(?:css(\.map)?|js(\.map)?|jpe?g|png|gif|ico|cur|heic|webp|tiff?|mp3|m4a|aac|ogg|midi?|wav|mp4|mov|webm|mpe?g|avi|ogv|flv|wmv)$ {
            expires 7d;
            access_log off;
        }

        location ~* \.(?:svgz?|ttf|ttc|otf|eot|woff2?)$ {
            add_header Access-Control-Allow-Origin "*";
            expires 7d;
            access_log off;
        }

        location = /favicon.ico {
            log_not_found off;
            access_log off;
        }

        location = /robots.txt {
            log_not_found off;
            access_log off;
        }

        location / {
            try_files /does_not_exists @fallback;
        }

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

    #   PHP
        location @fallback {
            proxy_pass http://127.0.0.1:8080;
            proxy_redirect http://127.0.0.1:8080 /;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            access_log off;
       }

    #   PHP-FPM
        location @fallback {
            index index.php index.html index.htm; 
            fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $root_path$fastcgi_script_name;
            include fastcgi_params;
            fastcgi_param DOCUMENT_ROOT $root_path;
       }
}


Create a folder to store the cache:



mkdir /var/cache/nginx_pagespeed/
chown www-data:www-data /var/cache/nginx_pagespeed/


We check the Nginx configuration and apply the settings:



nginx -t
nginx -s reload



All Articles