Te reja dhe Aktivitete

WordPress translate month names


function translate_archive_month($list) {
$patterns = array(
'/January/', '/February/', '/March/', '/April/', '/May/', '/June/',
'/July/', '/August/', '/September/', '/October/', '/November/', '/December/'
);
$replacements = array(
'Janar', 'Shkurt', 'Mars', 'Prill', 'Maj', 'Qershor',
'Korrik', 'Gusht', 'Shtator', 'Tetor', 'Nentor', 'Dhjetor'
);
$list = preg_replace($patterns, $replacements, $list);
return $list;
}

How to Setup SSL in Varnish Cache

I don’t think it is necessary to explain what a Varnish Cache is and how it affects the load speed of the site. At least not in this post. If you are here, I suppose that you want to know how to setup SSL in Varnish.

In fact, the developer of Varnish finds it a bad idea to implement SSL support. But there are still several ways to tackle this issue.

Option 1

First, you need to understand whether it is possible to handle SSL with another service and leave communication with the server on which Varnish is installed at the default port.

Example: DigitalOcean offers Fully Managed SSL Certificates. In other words, you can create a Load Balancer and configure SSL.

Then, create a droplet on the internal network (without access from the outside), raise the environment (Varnish and other software), and attach it to the Load Balancer.

But before you start, I want to highlight that you should make sure that your hosting provider offers some solutions (Cloud Flare, etc).

Option 2

Let’s imagine that we have to raise the environment to implement the API (monolith) on Laravel Framework, and we have our own VPS with root access.

The process looks like this:

  • Nginx handles the 443 port, handles static assets and proxy other requests to another Varnish Cache:6081.
  • Varnish checks the cache, and if not then proxy request to the backend (Nginx: 81, why Nginx and not PHP I will write below), gets the result, caches, and gives Nginx.
  • Nginx: 81 handle requests and run PHP on 9000 port or a socket.
  • PHP launches Laravel… It’s no longer interesting to us, we’ve known it for a long time.

So the scheme in short:

Nninx: 443 -> Varnish: 6081 -> Nginx: 81 -> PHP: 9000

Why doesn’t Varnish apply directly to PHP? Because PHP-FPM does not understand Varnish requests, and you will most likely get a 503 error.

Laravel, by the way, is a good solution since they “play nice together.”

I will skip boring guides on installing LEMP and concentrate your attention on configs.

Virtualhost for Nginx: /etc/nginx/conf.d/api.myserver.com.conf

server {

    listen 443;

    server_name www.api.myserver.com api.myserver.com;
    
    access_log   /var/log/nginx/access.log;
    error_log    /var/log/nginx/error.log;

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

    location / {
        proxy_pass http://127.0.0.1:6081;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header HTTPS "on";
    }

   location ~ /\.ht {
       deny all;
   }

   location ~ /.well-known {
       allow all;
   }

    # I used letsencrypt service )

    ssl_certificate /etc/letsencrypt/live/myserver.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/myserver.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
}

server {

    listen 80;

    server_name  www.api.myserver.com api.myserver.com;

    return 301 https://www.$host$request_uri;

}

server {

    listen 81;

    server_name api.myserver.com www.api.myserver.com;

    root /var/www/api/public;

    index index.php;

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

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ .php$ {
	    include snippets/fastcgi-php.conf;
        fastcgi_param HTTPS on;
        fastcgi_pass   127.0.0.1:9000; # OR unix:/var/run/php7.4-fpm.sock;
    }
}

I used this template. You just have to modify the backend port.

# /etc/varnish/default.vcl
...

backend server1 { # Define one backend
  .host = "127.0.0.1";    # IP or Hostname of backend
  .port = "81";           # Port Nginx or whatever is listening
  .max_connections = 300; # That's it

...

/etc/default/varnish

...

DAEMON_OPTS="-a :6081 \ # input
             -T localhost:6082 \ # admin
             -f /etc/varnish/default.vcl \ # proxy conf
             -S /etc/varnish/secret \ # secret conf
             -s malloc,256m" 

...

That’s all. Those simple maneuvers can significantly accelerate a project. I hope this little guide will help you save your time and reduce your suffering.

Nginx, Varnish and WordPress with SSL Termination

Assuming you’ve already got your reverse proxy running, in wp-config.php add the following:


/** TLS/HTTPS fixes **/
// in some setups HTTP_X_FORWARDED_PROTO might contain a comma-separated list
// e.g. http,https so check for https existence.
if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false) {
    // update HTTPS server variable to always 'pretend' incoming requests were 
    // performed via the HTTPS protocol.
    $_SERVER['HTTPS']='on';
}


server {
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2;
server_name afrim.com www.afrim.com;
port_in_redirect off;

ssl on;
ssl_certificate /etc/nginx/ssl/afrim_com_crt.crt;
ssl_certificate_key /etc/nginx/ssl/afrim_com.key;

location / {
proxy_pass http://127.0.0.1:80;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header HTTPS "on";
}
}

server {
listen 8080;
listen [::]:8080;
server_name afrim.com www.afrim.com;
root /var/www/html/;
index index.php;
port_in_redirect off;

location / {
try_files $uri $uri/ /index.php?$args;
}

location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}

}

server {
listen 8080;
listen [::]:8080;
server_name afrim.com www.afrim.com;
return 301 https://afrim.com$request_uri;
}

—————————–


vcl 4.1;

import proxy;

backend default {
.host = "127.0.0.1";
.port = 8080;
}

sub vcl_recv {
if ((req.http.X-Forwarded-Proto && req.http.X-Forwarded-Proto != "https") ||
(req.http.Scheme && req.http.Scheme != "https")) {
return (synth(750));
} elseif (!req.http.X-Forwarded-Proto && !req.http.Scheme && !proxy.is_ssl()) {
return (synth(750));
}
}

sub vcl_synth {
if (resp.status == 750) {
set resp.status = 301;
set resp.http.location = "https://" + req.http.Host + req.url;
set resp.reason = "Moved";
return (deliver);
}
}

Paginating an Advanced Custom Fields Repeater

Hands down my favourite WordPress plugin is Elliot Condon’s Advanced Custom Fields, and it’s made even more powerful by the Repeater Field add-on. But a Repeater can get unwieldy when it contains a large number of items, and you might find yourself wanting to paginate the results when you display them to the user. Here’s a technique for doing that.

In this example we will paginate a Repeater image gallery mapped to a custom field named image_gallery with a sub field named image which contains an image object. Our Repeater will be displayed on a page at the URL /gallery.

10 images will be displayed per page, and pagination links will allow the user to navigate between the gallery’s pages at pretty URLS such as /gallery/2//gallery/3/ and so on.

If you’re wondering what special magic you need to perform to get those pretty permalinks working, the answer is… none! WordPress automagically converts URL segments such as /2/ into a query variable named "page". Very handy!

In your page template:

[php]

/* * Paginate Advanced Custom Field repeater */ if( get_query_var(‘page’) ) { $page = get_query_var( ‘page’ ); } else { $page = 1; } // Variables $row = 0; $images_per_page = 10; // How many images to display on each page $images = get_field( ‘image_gallery’ ); $total = count( $images ); $pages = ceil( $total / $images_per_page ); $min = ( ( $page * $images_per_page ) $images_per_page ) + 1; $max = ( $min + $images_per_page ) 1; // ACF Loop if( have_rows( ‘image_gallery’ ) ) : ?> while( have_rows( ‘image_gallery’ ) ): the_row(); $row++; // Ignore this image if $row is lower than $min if($row < $min) { continue; } // Stop loop completely if $row is higher than $max if($row > $max) { break; } ?> $img_obj = get_sub_field( ‘image’ ); ?> <a href= echo $img_obj[‘sizes’][‘large’]; ?>> <img src= echo $img_obj[‘sizes’][‘thumbnail’]; ?> alt=> a> endwhile; // Pagination echo paginate_links( array( ‘base’ => get_permalink() .%#%’ . ‘/’, ‘format’ =>?page=%#%’, ‘current’ => $page, ‘total’ => $pages ) ); ?> else: ?> No images found endif; ?>

[/php]

A note about Custom Post Types

This technique will also work on Custom Post Type single templates. Your pagination permalinks will have the format /post-type/post-slug/2/.

Credits

My solution was inspired by Elliot Condon and Twansparent’s contributions to the Advanced Custom Fields forum.

Introduction to Installing htop on CentOS 7

any sysadmins know about top, the standard process management and activity monitor that comes on most Linux systems. But there are times when top does not provide the information you’re really looking for, or you want something that updates more frequently as the state of your system changes.

 

Look no further than htop. It’s interactive, real-time, and sports a variety of metrics and details above and beyond what top provides.

 

You can see CPU utilization at a glance, and that’s just the tip of the iceberg. Sort processes, kill rogue jobs right from htop, and set priorities. To learn more about htop, see the htop website.

Prerequisites to Installing htop on CentOS 7

To install htop on CentOS 7, you’ll need a few things:

 

  • A CentOS 7 machine
  • Basic knowledge of Linux and how to use the shell

Installing htop on CentOS 7: Two Methods

There are two different ways you can get htop on your computer. First, you can install it as a binary from your package manager (on CentOS this would be yum). This is a good option if you want to get it right away and don’t much mind what version of htop you’re getting.

 

You can also install htop from source. Since htop is open-source, you can download the code and build it yourself on your system. This takes a little longer, but you can be sure you’re getting the most updated build available (important if you’re looking for a specific new feature).

 

We’ll go through both methods step by step.

Install htop with Yum

The yum package manager does not contain htop by default. This is okay; we just need to add an EPEL repository so yum can find it. Here’s the commands to add that repository:

 

yum -y install epel-release

yum -y update

 

Now with the repository properly added, you can tell yum to install the htop process monitoring tool:

 

yum -y install htop

If the installation completes successfully, you should be able to type htop at the command line and see the status of your system.

(source: htop screenshots)

To learn more about htop’s features and how to customize it, see the htop website or htop explained.

Install htop from Source

To ensure you have the most recent version of htop and all the new features, you can install htop from source. This involves downloading the source code and building it on your machine.

 

Installing from source means you need to gather the dependencies yourself. Before we can install htop, we’ll need Development Tools (gcc and other compilers) and ncurses.

 

yum groupinstall “Development Tools”

yum install ncurses ncurses-devel

 

With the dependencies installed, we can grab the source code and extract it:

 

wget http://hisham.hm/htop/releases/2.0.2/htop-2.0.2.tar.gz

tar xvfvz htop-2.0.2.tar.gz

cd htop-2.0.2

 

Now that we’re in the folder with the htop source code, we can run these three commands to prepare and build the code:

 

./configure

make

make install

 

Once the make install step completes, you should be able to use htop. Try typing htop into your terminal and you should see the system monitor appear.

 

If you get a htop: command not found error, you’ll need to specify the location of the htop executable in your PATH.

Conclusion: htop on CentOS7 Installed

There’s so much you can do with htop, and we hope it will help monitor your processes more quickly and easily. As always, if you have questions please leave them in the comments below.

Apache SSL Termination (HTTPS Varnish cache)

General approach

Varnish configuration

...
backend default {
    .host = "127.0.0.1";
    .port = "8080";
}
...

Apache configuration


  ServerName localhost.com
  DocumentRoot /var/www/magento/pub

    RequestHeader set X-Forwarded-Proto "https"
    ServerName localhost.com

    SSLEngine On
    SSLCertificateFile /etc/apache2/ssl/cert.crt
    SSLCertificateKeyFile /etc/apache2/ssl/cert.key

    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:80/
    ProxyPassReverse / http://127.0.0.1:80/

Apache modules

sudo a2enmod ssl
sudo a2enmod rewrite
sudo a2enmod headers
sudo a2enmod proxy
sudo a2enmod proxy_balancer
sudo a2enmod proxy_http
sudo service apache2 restart

 

How To Install Nginx on Ubuntu 20.04

Introduction

Nginx is one of the most popular web servers in the world and is responsible for hosting some of the largest and highest-traffic sites on the internet. It is a lightweight choice that can be used as either a web server or reverse proxy.

In this guide, we’ll discuss how to install Nginx on your Ubuntu 20.04 server, adjust the firewall, manage the Nginx process, and set up server blocks for hosting more than one domain from a single server.

Prerequisites

Before you begin this guide, you should have a regular, non-root user with sudo privileges configured on your server. You can learn how to configure a regular user account by following our Initial server setup guide for Ubuntu 20.04.

You will also optionally want to have registered a domain name before completing the last steps of this tutorial. To learn more about setting up a domain name with DigitalOcean, please refer to our Introduction to DigitalOcean DNS.

When you have an account available, log in as your non-root user to begin.

Step 1 – Installing Nginx

Because Nginx is available in Ubuntu’s default repositories, it is possible to install it from these repositories using the apt packaging system.

Since this is our first interaction with the apt packaging system in this session, we will update our local package index so that we have access to the most recent package listings. Afterwards, we can install nginx:

  1. sudo apt update
  2. sudo apt install nginx

After accepting the procedure, apt will install Nginx and any required dependencies to your server.

Step 2 – Adjusting the Firewall

Before testing Nginx, the firewall software needs to be adjusted to allow access to the service. Nginx registers itself as a service with ufw upon installation, making it straightforward to allow Nginx access.

List the application configurations that ufw knows how to work with by typing:

  1. sudo ufw app list

You should get a listing of the application profiles:

Output
Available applications:
  Nginx Full
  Nginx HTTP
  Nginx HTTPS
  OpenSSH

As demonstrated by the output, there are three profiles available for Nginx:

  • Nginx Full: This profile opens both port 80 (normal, unencrypted web traffic) and port 443 (TLS/SSL encrypted traffic)
  • Nginx HTTP: This profile opens only port 80 (normal, unencrypted web traffic)
  • Nginx HTTPS: This profile opens only port 443 (TLS/SSL encrypted traffic)

It is recommended that you enable the most restrictive profile that will still allow the traffic you’ve configured. Right now, we will only need to allow traffic on port 80.

You can enable this by typing:

  1. sudo ufw allow ‘Nginx HTTP’

You can verify the change by typing:

  1. sudo ufw status

The output will indicated which HTTP traffic is allowed:

Output
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 your Web Server

At the end of the installation process, Ubuntu 20.04 starts Nginx. The web server should already be up and running.

We can check with the systemd init system to make sure the service is running by typing:

  1. systemctl status nginx
Output
● 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 Fri 2020-04-20 16:08:19 UTC; 3 days ago
     Docs: man:nginx(8)
 Main PID: 2369 (nginx)
    Tasks: 2 (limit: 1153)
   Memory: 3.5M
   CGroup: /system.slice/nginx.service
           ├─2369 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
           └─2380 nginx: worker process

As confirmed by this out, the service has started successfully. However, the best way to test this is to actually request a page from Nginx.

You can access the default Nginx landing page to confirm that the software is running properly by navigating to your server’s IP address. If you do not know your server’s IP address, you can find it by using the icanhazip.com tool, which will give you your public IP address as received from another location on the internet:

  1. curl -4 icanhazip.com

When you have your server’s IP address, enter it into your browser’s address bar:

http://your_server_ip

You should receive the default Nginx landing page:

Nginx default page

If you are on this page, your server is running correctly and is ready to be managed.

Step 4 – Managing the Nginx Process

Now that you have your web server up and running, let’s review some basic management commands.

To stop your web server, type:

  1. sudo systemctl stop nginx

To start the web server when it is stopped, type:

  1. sudo systemctl start nginx

To stop and then start the service again, type:

  1. sudo systemctl restart nginx

If you are only making configuration changes, Nginx can often reload without dropping connections. To do this, type:

  1. sudo systemctl reload nginx

By default, Nginx is configured to start automatically when the server boots. If this is not what you want, you can disable this behavior by typing:

  1. sudo systemctl disable nginx

To re-enable the service to start up at boot, you can type:

  1. sudo systemctl enable nginx

You have now learned basic management commands and should be ready to configure the site to host more than one domain.

When using the Nginx web server, server blocks (similar to virtual hosts in Apache) can be used to encapsulate configuration details and host more than one domain from a single server. We will set up a domain called your_domain, but you should replace this with your own domain name.

Nginx on Ubuntu 20.04 has one server block enabled by default that is configured to serve documents out of a directory at /var/www/html. While this works well for a single site, it can become unwieldy if you are hosting multiple sites. Instead of modifying /var/www/html, let’s create a directory structure within /var/www for our your_domain site, leaving /var/www/html in place as the default directory to be served if a client request doesn’t match any other sites.

Create the directory for your_domain as follows, using the -p flag to create any necessary parent directories:

  1. sudo mkdir -p /var/www/your_domain/html

Next, assign ownership of the directory with the $USER environment variable:

  1. sudo chown -R $USER:$USER /var/www/your_domain/html

The permissions of your web roots should be correct if you haven’t modified your umask value, which sets default file permissions. To ensure that your permissions are correct and allow the owner to read, write, and execute the files while granting only read and execute permissions to groups and others, you can input the following command:

  1. sudo chmod -R 755 /var/www/your_domain

Next, create a sample index.html page using nano or your favorite editor:

  1. sudo nano /var/www/your_domain/html/index.html

Inside, add the following sample HTML:

/var/www/your_domain/html/index.html
<html>
    <head>
        <title>Welcome to your_domain!title>
    head>
    <body>
        <h1>Success!  The your_domain server block is working!h1>
    body>
html>

Save and close the file by pressing Ctrl+X to exit, then when prompted to save, Y and then Enter.

In order for Nginx to serve this content, it’s necessary to create a server block with the correct directives. Instead of modifying the default configuration file directly, let’s make a new one at /etc/nginx/sites-available/your_domain:

  1. sudo nano /etc/nginx/sites-available/your_domain

Paste in the following configuration block, which is similar to the default, but updated for our new directory and domain name:

/etc/nginx/sites-available/your_domain
server {
        listen 80;
        listen [::]:80;

        root /var/www/your_domain/html;
        index index.html index.htm index.nginx-debian.html;

        server_name your_domain www.your_domain;

        location / {
                try_files $uri $uri/ =404;
        }
}

Notice that we’ve updated the root configuration to our new directory, and the server_name to our domain name.

Next, let’s enable the file by creating a link from it to the sites-enabled directory, which Nginx reads from during startup:

  1. sudo ln -s /etc/nginx/sites-available/your_domain /etc/nginx/sites-enabled/

Note: Nginx uses a common practice called symbolic links, or symlinks, to track which of your server blocks are enabled. Creating a symlink is like creating a shortcut on disk, so that you could later delete the shortcut from the sites-enabled directory while keeping the server block in sites-available if you wanted to enable it.

Two server blocks are now enabled and configured to respond to requests based on their listen and server_name directives (you can read more about how Nginx processes these directives here):

  • your_domain: Will respond to requests for your_domain and www.your_domain.
  • default: Will respond to any requests on port 80 that do not match the other two blocks.

To avoid a possible hash bucket memory problem that can arise from adding additional server names, it is necessary to adjust a single value in the /etc/nginx/nginx.conf file. Open the file:

  1. sudo nano /etc/nginx/nginx.conf

Find the server_names_hash_bucket_size directive and remove the # symbol to uncomment the line. If you are using nano, you can quickly search for words in the file by pressing CTRL and w.

Note: Commenting out lines of code – usually by putting # at the start of a line – is another way of disabling them without needing to actually delete them. Many configuration files ship with multiple options commented out so that they can be enabled or disabled, by toggling them between active code and documentation.

/etc/nginx/nginx.conf
...
http {
    ...
    server_names_hash_bucket_size 64;
    ...
}
...

Save and close the file when you are finished.

Next, test to make sure that there are no syntax errors in any of your Nginx files:

  1. sudo nginx -t

If there aren’t any problems, restart Nginx to enable your changes:

  1. sudo systemctl restart nginx

Nginx should now be serving your domain name. You can test this by navigating to http://your_domain, where you should see something like this:

Nginx first server block

Step 6 – Getting Familiar with Important Nginx Files and Directories

Now that you know how to manage the Nginx service itself, you should take a few minutes to familiarize yourself with a few important directories and files.

Content

  • /var/www/html: The actual web content, which by default only consists of the default Nginx page you saw earlier, is served out of the /var/www/html directory. This can be changed by altering Nginx configuration files.

Server Configuration

  • /etc/nginx: The Nginx configuration directory. All of the Nginx configuration files reside here.
  • /etc/nginx/nginx.conf: The main Nginx configuration file. This can be modified to make changes to the Nginx global configuration.
  • /etc/nginx/sites-available/: The directory where per-site server blocks can be stored. Nginx will not use the configuration files found in this directory unless they are linked to the sites-enabled directory. Typically, all server block configuration is done in this directory, and then enabled by linking to the other directory.
  • /etc/nginx/sites-enabled/: The directory where enabled per-site server blocks are stored. Typically, these are created by linking to configuration files found in the sites-available directory.
  • /etc/nginx/snippets: This directory contains configuration fragments that can be included elsewhere in the Nginx configuration. Potentially repeatable configuration segments are good candidates for refactoring into snippets.

Server Logs

  • /var/log/nginx/access.log: Every request to your web server is recorded in this log file unless Nginx is configured to do otherwise.
  • /var/log/nginx/error.log: Any Nginx errors will be recorded in this log.

Conclusion

Now that you have your web server installed, you have many options for the type of content to serve and the technologies you want to use to create a richer experience.

If you’d like to build out a more complete application stack, check out the article How To Install Linux, Nginx, MySQL, PHP (LEMP stack) on Ubuntu 20.04.

In order to set up HTTPS for your domain name with a free SSL certificate using Let’s Encrypt, you should move on to How To Secure Nginx with Let’s Encrypt on Ubuntu 20.04.

How To Configure Varnish Cache with Apache Reverse Proxy and SSL Termination

In this guide, we will show you how to install and configure the Varnish cache for the Apache webserver with SSL termination. One limitation of Varnish Cache is that it is designed to accelerate HTTP, not the secure HTTPS protocol. Therefore, some workarounds must be performed to allow Varnish to work on SSL enabled website.

SSL/TLS Termination is the process of decrypting SSL-encrypted traffic. In our case, Apache acts like a proxy server and intermediary point between the client and Varnish and is used to convert HTTPS to HTTP.

tep 1. Install and Configure Apache (Backend) on CentOS/RHEL 8

We had CentOS 8 installed on our web server, which uses dnf package manager. However, if you are familiar with Linux systems, you can apply this manual almost entirely to other OS, such as Centos 7 (use yum) or Ubuntu and Debian (use apt instead).

1. Install Apache, start it automatically at boot, and launch

sudo dnf install httpd
sudo systemctl enable httpd
sudo systemctl start httpd
sudo systemctl status httpd

2. Create a directory for your website and grant permissions

Make sure to replace the “example.com” with your domain name:

sudo mkdir -p /var/www/example.com/public_html
sudo mkdir -p /var/www/example.com/log
sudo mkdir -p /var/www/example.com/ssl

Use aux | grep httpd or ps aux | grep apache to see what user Apache is using on your system.

In our case, the Apache user is “apache” (you may see “www-data” or other username displayed), therefore we will run the following commands to grant necessary permissions:

sudo chown -R apache:apache /var/www/
sudo chmod -R 750 /var/www

3. Create a dummy index file in your domain’s document root directory

echo 'Hello, World!' > /var/www/example.com/public_html/index.html

4. Create a new virtual host file and restart Apache

sudo mkdir /etc/httpd/sites-available
sudo mkdir /etc/httpd/sites-enabled

Tell Apache to look for virtual hosts in the sites-enabled directory:

sudo vi /etc/httpd/conf/httpd.conf

Add this line at the end of httpd.conf file:

IncludeOptional sites-enabled/*.conf

Create the new virtual host file:

sudo vi /etc/httpd/sites-available/example.com.conf
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public_html
    ErrorLog /var/www/example.com/error.log
    CustomLog /var/www/example.com/requests.log combined
</VirtualHost>

Enable the new virtual host files

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

Restart Apache

sudo systemctl restart httpd

Open access to the HTTP service in the firewall

systemctl restart firewalld
systemctl enable firewalld.service
firewall-cmd --state
firewall-cmd --zone=public --permanent --add-service=http
firewall-cmd --reload

Open your domain in the web browser to see the “Hello, World!” message, e.g.:

http://example.com or http://example.com:80

 

Step 2. Install and Configure Varnish Cache

1. Install Varnish Cache

dnf module install varnish

Change the default Varnish Listen port from 6081 to 80.

sudo vi /etc/systemd/system/varnish.service

Find the following line:

ExecStart=/usr/sbin/varnishd -a :6081 -f /etc/varnish/default.vcl -s malloc,256m

And replace it with this one:

ExecStart=/usr/sbin/varnishd -a :80 -f /etc/varnish/default.vcl -s malloc,256m

Save changes.

Check the default Varnish backend IP and port.

sudo vi /etc/varnish/default.vcl

It should look like this:

backend default {
    .host = "127.0.0.1";
    .port = "8080";
}

2. Change the default apache HTTP port 80 to 8080 (or any other port of your choice)

sudo vi /etc/httpd/conf/httpd.conf

Find the following line:

Listen 80

And replace it with this one:

Listen 8080

Save changes.

Open your virtual host file:

sudo vi /etc/httpd/sites-available/example.com.conf

Find the following line:

*:80>
ServerName example.com

And replace it with this one:

127.0.0.1:8080>
ServerName example.com

Save changes.

Launch Varnish, start it automatically at boot and check service status

varnishd -V
sudo systemctl start varnish
sudo systemctl enable varnish
sudo systemctl status varnish

Restart Apache

sudo systemctl restart httpd

Open your website in browser to see the “Hello, World!” message, e.g.:

http://example.com

Varnish cache installation and configuration process
Step 2. Diagram

Step 3. Configure Apache HTTP Server As Reverse-Proxy

1. Create SSL certificate for Apache

For the purpose of this tutorial, we will create self-signed SSL certificates. Nevertheless, you can also install free let’s encrypt certificates using this online manual.

First, you have to be sure that the mod_ssl Apache module is installed on the server.

dnf install epel-release
sudo dnf install openssl mod_ssl
sudo systemctl restart httpd

Check if mod SSL is enabled:

apachectl -M | grep ssl
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /var/www/example.com/ssl/apache-selfsigned.key -out /var/www/example.com/ssl/apache-selfsigned.crt

2. Setting up new Apache virtual host for SSL communication

Open your virtual host file:

sudo vi /etc/httpd/sites-available/example.com.conf

Add a new proxy virtual host that will listen to 443 port and redirect all traffic to Varnish (port 80), e.g. perform SSL termination.

<VirtualHost 127.0.0.1:8080>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public_html
    ErrorLog /var/www/example.com/error.log
    CustomLog /var/www/example.com/requests.log combined
</VirtualHost>


<VirtualHost *:443>
    ServerName varnishtest2.plumrocket.net
    RequestHeader set X-Forwarded-Proto "https"

    ErrorLog /var/log/httpd/external-https_error.log
    CustomLog /var/log/httpd/external-https_access.log combined

    SSLEngine On
    SSLCertificateFile /etc/ssl/certs/apache-selfsigned.crt
    SSLCertificateKeyFile /etc/ssl/certs/apache-selfsigned.key

    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:80/
    ProxyPassReverse / http://127.0.0.1:80/
</VirtualHost>

Save changes and restart Apache

sudo systemctl restart httpd
Configuration of Apache HTTP Server As Reverse-Proxy
Step 3. Diagram

Step 4. Testing

Open your domain in the web browser to test if the Varnish Cache is working properly:

https://example.com

Run one of the following three commands from shell to test varnish while simultaneously refreshing the web page:

varnishlog
varnishtop
varnishstat

Enter Ctrl + C to stop the above commands from running.

If you experience any errors, it’s always wise to test each portion of our setup separately. If you look at diagram 3 above, you will see that our setup consists of 3 logical sections – Apache frontend, Varnish, and Apache backend.

Test Apache backend to see if the virtual host is accessible from the shell:

curl http://127.0.0.1:8080/

Test Varnish Cache to see if it is accessible from the shell:

curl http://127.0.0.1:80/

Finally, test the Apache frontend from the shell:

curl https://127.0.0.1/

Summary

Varnish is useful to speed up site load time and we oftentimes suggest our clients optimize their Magento store performance. Please don’t hesitate to contact us if you need assistance speeding up your Magento store. If you find this tutorial useful, please like and share it with the world.

 

Varnish Cache

#!/bin/sh
sudo -i
apt update && apt upgrade
#Install Apache webserver
apt install apache2
systemctl start apache2
systemctl status apache2
#Being a webserver, Apache listens on port 80 by default. Use the netstat command as shown to verify this.
sudo netstat -pnltu
#Install Varnish HTTP Accelerator
apt install varnish
systemctl start varnish
systemctl status varnish
#Configuring Apache and Varnish HTTP Cache
nano /etc/apache2/ports.conf
listen to port 80 to 8080
nano /etc/apache2/sites-enabled/000-default.conf
listen to port 80 to 8080
systemctl restart apache2
#Setting up Varnish to listen to port 80
nano /etc/default/varnish
Scroll and locate the attribute ‘DAEMON_OPTS’. Be sure to change the port from 6081 to port 80
#If you check the /etc/varnish/default.vcl file, you should get the output shown below.
nano /etc/varnish/default.vcl
#Lastly, we need to edit the /lib/systemd/system/varnish.service and modify the port in ExecStart directive from port 6081 to 80.
nano /lib/systemd/system/varnish.service
Locate the ExecStart directive and change the port from port 6081 to 80.
systemctl restart apache2
systemctl daemon-reload
systemctl restart varnish
#Testing the Configuration
curl -I server_IP
Free Web Hosting