Author: RunCloud Team

  • How to Copy Files in Linux and Overwrite without Confirmation

    How to Copy Files in Linux and Overwrite without Confirmation

    Are you working on a bash script that needs to be executed without any human inputs? Do your scripts fail when the process of copying files encounters a problem?

    If you answered “yes” to either of these questions then you’re in the right place.

    In this post, we will take a quick look at the cp command in Linux, and examine how it can be used in different scenarios.

    How to Copy Files in Linux CLI

    Copying files is one of the simplest actions that you can perform on a computer. To copy files via the command line you can use the cp command, which stands for ‘copy’. The general syntax for the cp command is:

    cp [OPTIONS] SOURCE(s)... DESTINATION

    The SOURCE(s) can be one or more files or directories, and the DESTINATION can be a single file or directory. If you’ve passed more than two parameters to the command, then the last one is always considered the destination, and all other parameters before it are considered the source(s).

    • If the DESTINATION is a directory, the SOURCE files or directories are copied into it.
    • If the DESTINATION is a file, the SOURCE file is copied and renamed as the DESTINATION file.

    Here is a simple example of how to copy a file named file.txt from the current directory to another directory named backup:

    cp file.txt backup/

    This will copy the file file.txt to the backup directory with the same name. If you want to copy the file with a different name, you can specify the new name after the backup directory:

    cp file.txt backup/new_file.txt

    This will copy the file file.txt to the backup directory as new_file.txt.

    How to Overwrite Existing Files

    By default, cp will overwrite any existing files in the destination without asking for confirmation. However, this behavior can be changed by using different flags or options with the cp command. Here are some of the common flags that can affect how cp handles overwriting:

    • -f or --force: This option will force cp to overwrite any existing files in the destination, even if they cannot be opened or removed. This option will also ignore any -n option that is used before it.

      For example, cp -f source.txt destination.txt will overwrite destination.txt with source.txt, regardless of any permissions or errors.
    • -i or --interactive: This option will make cp prompt the user before overwriting any existing files in the destination. You can choose to overwrite or skip the file by typing y or n and then pressing Enter.

      If you’re copying multiple files at once, you will be prompted for each file separately. If you don’t type anything and press Enter then the file will not be overwritten.

      This option will also override any -n option that is used before it. For example, cp -i source.txt destination.txt will ask the user if they want to overwrite destination.txt with source.txt, and proceed accordingly.
    • -n or --no-clobber: This option will prevent cp from overwriting any existing files in the destination. If the destination file already exists, cp will skip it and move on to the next file. This option will also override any -i option that is used before it.

      For example, cp -n source.txt destination.txt will not overwrite destination.txt with source.txt, if destination.txt already exists.
    • -u or --update: This option will make cp copy only when the source file is newer than the destination file, or when the destination file does not exist. This can be useful for updating or synchronizing files between different locations.

      For example, cp -u source.txt destination.txt will overwrite destination.txt with source.txt, only if source.txt is newer or destination.txt does not exist.

    Note that these flags can be combined to achieve different effects. For example, cp -uf source.txt destination.txt will force cp to overwrite destination.txt with source.txt, only if source.txt is newer or destination.txt does not exist.

    Changing the Default Behavior

    On some computers, the default behavior of the cp command can be affected by an alias. An alias is a way of creating a shortcut or a new name for a command, with some predefined options.

    For example, some Linux distributions come with the following alias pre-defined in their code:

    alias cp='cp -i'

    This means that whenever the user types cp, the shell will actually run cp -i, which will prompt the user before overwriting any files.

    Checking For An Existing Alias

    If you’re not sure whether your computer has a predefined alias, then you can run the following command to list all aliases, and then look to see whether the cp is present in the output:

    alias

    Removing An Alias

    To remove the alias for cp, you can run the command unalias cp, which will restore the default behavior of cp.

    Removing alias of copy command

    In the above example, we can see that an alias was defined for the cp command. After executing the unalias command, the alias entry was removed from the list.

    Temporarily Bypass An Alias

    If you don’t want to permanently remove the alias, you have an option to use a backslash before the cp command to bypass the alias and run the original command. For example, \cp source.txt destination.txt will overwrite destination.txt with source.txt, without prompting the user.

    bypassing alias of copy commands

    In the above example, we can see that the user was prompted for input when executing the copy operation, but not when the command was prefixed with the \ character.

    Automatically Accepting All Prompts

    In Linux there are multiple ways to do the same thing using different methods. If you don’t want to use the in-built -f option to overwrite files then you can use the copy command in conjunction with the yes command to automatically respond with y to all prompts.

    yes | cp -v source destination

    In the above example, we can see that the copy command prompted us for input before replacing each file, but the yes command responded ‘yes’ to each and every single one of them nearly instantaneously.

    Wrapping Up

    In this article, we have discussed how to copy files and directories in Linux via the command line. We have also explained different options and features of the copy command that are helpful in day-to-day usage.

    If you’re learning Linux to better manage your servers, we wish you all the best! However, you don’t need to be a Linux expert to host websites on the internet. RunCloud makes it extremely easy to deploy and manage websites using a user-friendly dashboard, and provides complete freedom to tinker under the hood.

    Whether you’re a beginner or a seasoned professional with decades of experience, sooner or later everyone makes a configuration change that completely renders websites useless. RunCloud has idiot-proofed many complex operations such as updating server configurations, installing SSL certificates, deleting applications, etc. – all of which makes it difficult for novice users to crash their website, and provides an extra set of guide-rails to advanced users.

    RunCloud is a versatile and reliable tool that can help you manage your server on your own, without the hassle and cost of hiring a system administrator. Don’t miss this opportunity to take your server management to the next level. Sign up for RunCloud today and enjoy the benefits of a cloud-based server management platform that is fast, secure, and easy to use.

  • Pipes vs Xargs: Which One To Use When Writing Bash Scripts In Linux

    Pipes vs Xargs: Which One To Use When Writing Bash Scripts In Linux

    Are you using Linux to manage your servers?

    Do you find yourself frequently copying the output on the terminal and pasting it into different bash commands?

    If you answered “Yes”, then you should definitely start using the Pipes and xargs command in Linux.

    These are extremely helpful Linux utilities that will save you time and effort when working with the command line. Using these opens up so many possibilities for manipulating and processing data in the command line.

    If you want to perform complex actions in the Linux terminal and grow your Linux skills past the basic level, you will definitely need to learn how to use these commands.

    In this article, you will learn exactly what xargs is, how it is different from pipes, and when to use which tool.

    Let’s get started!

    What Are Pipes in Linux?

    Pipes are a way of connecting the standard output of one command to the standard input of another command in Linux. This allows you to chain commands together and process data in a stream.

    To understand pipes, imagine two people talking on a ‘tin can telephone’. Here the first person is passing some information and the second person can only hear the information being passed. In this example, the telephone is acting as a pipe and the second person cannot jump to the end of the conversation without listening to the entire conversation first.

    To understand pipes, you can imagine two people talking on a ‘tin can telephone’. Here the first person is passing some information and the second person can only hear the information being passed. In this example, the telephone is acting as a pipe and the second person can not jump to the end of the conversation without listening to the entire conversation first.

    Similarly, pipes allow you to pass along information between processes and help you manipulate and process data in various ways. The syntax of pipes in pretty simple, just put a | sign between two commands.

    first | second

    In the above example, the output of the first will be used as the input for the second. This is pretty useful when working in the CLI.

    For example, if you want to count the number of files and directories in the current directory, you can use a pipe like this:

    ls | wc -l

    This command will list all files and directories in the current directory, and then pipe the output to the wc command, which will count the number of lines. The pipe character | is used to redirect the output of command to the other. The command on the left side of the pipe sends its output to the command on the right side of the pipe, which receives it as its input.

    Pipes are useful for performing operations on multiple items of data without having to write a loop or a script. You can also use multiple pipes to create a pipeline of commands, such as:

    find . -name "*.txt" | grep "hello" | wc -l

    The above command will find all files in the current directory and its subdirectories that have the “.txt” extension, and then pass them to the grep command, which will filter only the files that contain the word “hello”. The output of the grep command will then be piped to the wc command, which will count the number of lines. The result of this command is the number of files that have the “.txt” extension and the word “hello” in them.

    What is the xargs Command?

    The xargs utility in Linux reads data from standard input and converts it into command line arguments for another command. This allows you to perform operations on large amounts of data without having to write a loop or a script.

    For most part, this is pretty similar to the pipe operator that we discussed above, but with one major difference. The pipe operator redirects its output to the standard input of the second command, whereas the xargs utility will create a list of all the data and then pass it as command line arguments to the second command.

    To understand this, imagine the same person from above writing the information on a piece of paper and then passing it along to the second person. In this example, the paper is the xargs utility and the second person can see all the information at once.

    Xargs work in Linux by compiling a list of arguments.

    Having the ability to pass along information via the command line arguments opens up many possibilities. For example, if you want to delete all files that have the word “temp” in their name, you can use xargs like this:

    find . -name "*temp*" | xargs rm

    This command will find all files in the current directory and its subdirectories that have “temp” in their name, and then pass them as arguments to the rm command, which will delete them.

    Xargs or Pipes: Which One to Use?

    You may have already spotted that these two commands are basically the same apart from one key detail – pipes are useful for processing data in a stream.

    The main difference between pipes and xargs is that pipes pass data as standard input, while xargs passes data as command line arguments.

    This means that pipes will only work with commands that accept standard input, while xargs can only work with commands that accept command line arguments.

    What Are Standard Input and Command Line Arguments?

    Standard input and command line arguments are two different ways of passing data to a program in Linux.

    • Standard input is a stream of data that the program reads from its standard input file descriptor, usually the keyboard or a pipe.
    • Command line arguments are strings of text that the program receives as parameters when it is invoked from the shell.

    For example, if you run the command ls -l /home, the program ls will receive two command line arguments: -l and /home. The program can access these arguments using the argc and argv variables in C, or equivalent mechanisms in other languages.

    Although many software tools accept both command line arguments and standard input, not all do. As a software user, we often do not have the option to change how the program processes input.

    For example, the command echo will print whatever you type after it, but it will not read from standard input. If you try to pipe the output of ls to echo, you will get nothing:

    ls | echo

    This is where xargs comes in handy – xargs will take the data from standard input and convert it into arguments for the command you specify. For example, if you want to print the names of all files and directories in the current directory, you can use xargs with echo like this:

    ls | xargs echo

    This command will list all files and directories in the current directory, and then pass them as arguments to the echo command, which will print them.

    The choice of using pipes or xargs depends on the situation and the commands you want to use. In general, pipes are more efficient and elegant, as they avoid creating intermediate files or processes.

    However, xargs can be more flexible and powerful, as it allows you to customize the arguments and options for the command you want to execute. It also has many options that allow you to handle different scenarios, such as limiting the number of arguments, replacing placeholders, prompting the user, or dealing with filenames that contain spaces or special characters. Let’s see some of these use cases in the next section.

    How to Use xargs like a Pro in Linux

    xargs has many options that allow you to customize its behavior and handle different situations. Here are some of the most common and useful ones:

    Limit the Number of Arguments

    The -n option specifies the maximum number of arguments to pass to each invocation of the command. For example, if you want to print the names of all files and directories in the current directory in groups of three, you can use xargs with -n 3 like this:

    ls | xargs -n 3 echo

    This command will list all files and directories in the current directory, and then pass them as arguments to the echo command in groups of three. Then the echo command will be executed multiple times, once for each group of three arguments that it received.

    Replace Placeholder Text

    When working in the command line, you will often encounter cases where you need to run many simple commands, each with a tiny change. The -I option allows you to specify a placeholder that will be replaced by each argument in the command.

    For example, if you want to create many files in your server which follow a common pattern, then you can use xargs with -I {} like this:

    seq 12 | xargs -I {} touch runcloud_{}.txt

    The above command will create a sequence of twelve numbers, then use those numbers to create twelve files that follow the pattern runcloud_#.txt.

    Prompt User For Confirmation

    When generating commands on the fly, it is pretty easy to do irreversible damage to your server. The smart way to use xargs is by letting it generate all the commands and then manually confirming it before it can be executed.

    To do this, use the -p flag which prompts the user before executing each command and waits for confirmation. For example, if you want to delete all files that start with the word “runcloud”, but you want to confirm each deletion in batches of four, you can use xargs with -p like this:

    find . -name "runcloud*" | xargs -p -n 4 rm

    This command will find all files in the current directory and its subdirectories that have “runcloud” in their name, and then pass them as arguments to the rm command, which will prompt the user before deleting each file and wait for a “yes” or “no” answer.

    In the above example, we can see that first we created twelve files. Then we used the find function to find any files that match our criteria and then passed them along in batches of four. The resulting rm command is displayed in the terminal and we can press y or n to confirm or reject the action.

    After the command has been executed, we can see that the files in the second batch of deletion remain untouched because we pressed n when we were asked to confirm the deletion, whereas all the other files that matched the criteria were removed.

    Process Files with Weird Names

    The xargs utility is not secure, because it can execute arbitrary commands if the input contains malicious or unexpected data. For example, if the input contains spaces, quotes, or other special characters, xargs may interpret them as part of the command or the arguments, and cause unwanted or harmful effects.

    If you’re working with data that contains spaces, special characters, or even foreign language text, then it is always a good idea to terminate the output of a line using null characters to avoid unexpected output.

    The -0 or –null flag expects the input to be null-terminated, meaning that each argument is separated by a null character instead of a space or a newline. For example, if you want to delete all files that have the word “temp” in their name, but some of them have spaces in their name, you can use xargs with -0 like this:

    find . -name "runcloud*" -print0 | xargs -0 rm

    This command will find all files in the current directory and its subdirectories that start with “runcloud” and then print them with a null character after each name. xargs will then read the input as null-terminated and pass them as arguments to the rm command, which will delete them.

    In the above example, we can see that terminating the output with a null character allows the program to gracefully execute the given command. If we had omitted the null termination step, we would have encountered different errors.

    After Action Report

    Both pipe and xargs are powerful and versatile utilities that can help you perform different operations on data in the command line. There is a character limit to xargs, but it depends on the system and the options used.

    By default, it tries to pass as many arguments as possible to the command, without exceeding the maximum length of the command line. To see the limits of xargs on your system, you can use the --show-limits option.

    Normally, xargs runs the second command once, even if there is no input (output from the first command). This option is useful to avoid errors or unwanted actions when the input is empty. To suppress this, you can specify --no-run-if-empty option.

    These are just some of the options that xargs offers. You can find more information and examples by typing man xargs or xargs --help in the command line.

    It is clear that xargs is a must-learn tool for any Linux user who wants to go beyond the basics and explore the possibilities of the command line.

    However, if you don’t want to become a master in Linux command line utilities, but still want to manage your Linux server yourself, then you should check out RunCloud.

    RunCloud is a cloud-based server management platform that lets you deploy, configure, and monitor your web applications with ease. If you’re an advanced user, you can take advantage of the CLI and API, as RunCloud gives you full control over your server.

    If you’re not comfortable with using the CLI or the API, don’t worry. RunCloud also offers an easy to navigate dashboard that can deploy applications in a breeze. You can also use RunCloud to set up SSL certificates, domains, cron jobs, firewalls, and more.

    RunCloud is a versatile and reliable tool that can help you manage your server on your own, without the hassle and cost of hiring a system administrator. Don’t miss this opportunity to take your server management to the next level. Sign up for RunCloud today and enjoy the benefits of a cloud-based server management platform that is fast, secure, and easy to use.

  • A Simple Explanation of SSL Certificate Errors & How to Fix Them

    A Simple Explanation of SSL Certificate Errors & How to Fix Them

    SSL certificates are essential for ensuring the security and trust of your website visitors. However, occasionally you may encounter errors that prevent your website from loading properly, or from displaying the green padlock icon in the browser.

    In this article, we will explain exactly what SSL certificates are, why they are important, and how to fix some of the most common SSL certificate errors that you may encounter.

    What are SSL Certificates and Why are They Important?

    SSL stands for Secure Sockets Layer, which is an old protocol that was used to encrypt the data between a website and a browser. However, SSL has been replaced by a newer and more secure protocol called TLS, which stands for Transport Layer Security.

    TLS is the current standard for web security and it has several versions, such as TLS 1.2 and TLS 1.3. Although they are two different things, people use the terms TLS and SSL interchangeably because they perform the same function.

    An SSL certificate (or a TLS certificate) is a digital certificate that verifies the identity of a website and establishes a secure connection with the browser. These certificates are important for several reasons:

    • They protect your website by encrypting the data and preventing unauthorized access or tampering.
    • They boost your website’s credibility and reputation by showing your visitors that you care about their privacy and security.
    • They enhance your website’s SEO ranking by complying with Google’s algorithm, which favors HTTPS websites over HTTP ones.

    Check SSL/TLS Certificates

    Even the simplest of websites these days uses SSL certificates. If the certificate is installed correctly by the site owner, you probably won’t even notice it.

    In most browsers, the lock icon at the start of the address bar denotes that the website is being served over an encrypted connection.

    Google has recently phased out the ‘lock’ icon in favor of the ‘tune’ icon since this icon gave a false sense of security to visitors who don’t understand how the web works.

    These days, most modern browsers will alert you if you try to visit a site that does not support HTTPS. When you receive such a warning, you will need to manually click “Continue to Site” to visit the web page.

    Connection is not secure error caused by SSL error

    And even after you open the site, your browser will display a “Not Secure” badge in the address bar to remind you that the content on this website can be tampered with.

    Check your SSL

    Not all SSL certificates are equally trustworthy. Anyone can create a self-signed SSL certificate, but this does not mean that the website is legitimate or safe.

    To ensure the authenticity and security of a website, you need to get an SSL certificate from a trusted certificate authority (CA). For example, Google Trust Services is a third-party organization that validates your domain name and other information before issuing the certificate.

    A trusted CA is recognized by all major browsers, and it follows certain standards and policies to ensure the quality and security of the certificates. These certificates are installed on your computer by default, and updated automatically from time to time.

    RunCloud issues self-signed certificates to make it easier for you to test your websites without paying for a certificate. Since RunCloud is not a trusted CA, our root certificate is not installed on your computer; however, you can install it manually. Installing a root certificate on your computer will only take about 30 seconds, and you only need to do it once.Since it is relatively easy to modify root certificates on your computer, you might want to check if the certificates are properly installed using a third party service such as SSL Checker or GoDaddy SSL Certificate checker. These tools are a quick and easy way to validate your server settings in a human readable way.

    SSL certificate chain to mitigate errors

    The above example shows the certificate chain for ‘runcloud.io’. It shows when the certificate was issued, who issued the certificate, when it will expire, and other relevant information.

    How to Fix Common SSL Certificate Errors on Your Website

    Despite the benefits of SSL certificates, sometimes errors can occur, resulting in either issues with your website not loading properly, or preventing the green padlock icon from being displayed in the browser.

    These errors can be caused by various factors, such as incorrect SSL settings, expired or revoked certificates, mismatched domain names, mixed content, or network issues. Here are some of the most common SSL certificate errors and how to fix them.

    NET:ERR_CERT_AUTHORITY_INVALID

    This error means that the browser does not trust the SSL certificate for the website. This could happen if the certificate is self-signed, expired, or issued by an untrusted CA.

    To fix this error, you need to make sure that you have a valid SSL certificate from a reputable CA that is recognized by all major browsers. You can check the list of trusted CAs from the Mozilla Included CA Certificate List.

    You also need to make sure that your SSL certificate is installed correctly on your server, and that it includes all of the intermediate certificates that link your certificate to the root CA.

    NET::ERR_CERT_COMMON_NAME_INVALID

    You might encounter this error when the CN or SAN field of the SSL certificate does not match the domain name of your website. This could happen if the certificate is issued for a different domain, or if there are typos or misspellings in the CN or SAN fields.

    To fix this error, you need to make sure that you have a valid SSL certificate that covers all the domain names and subdomains that you want to secure with HTTPS.

    For example, if you want to secure ‘www.example.com’ and ‘blog.example.com’, you need to have a wildcard SSL certificate (*.example.com) or a multi-domain SSL certificate (www.example.com, blog.example.com).

    You also need to make sure that there are no typos or misspellings in the CN or SAN fields of your certificate.

    NET::ERR_CERT_REVOKED

    This error means that the SSL certificate has been revoked by the CA. This could happen if the certificate is compromised, misused, or no longer needed by the website owner.

    To fix this error, you need to contact your CA and find out why your certificate was revoked and how to get a new one. You also need to remove the revoked certificate from your server and install the new one as soon as possible.

    SSL Handshake Failed

    You might encounter this error when the browser and the server could not establish a secure connection using SSL. This could happen due to various reasons, such as incompatible SSL protocols, ciphers, or certificates, network issues, firewall settings, or server configuration errors.

    To fix this error, you need to troubleshoot the problem from both ends – meaning both the browser and the server.

    You can use Projects / SSL Client Test and How’s My SSL? to test your browser’s SSL support.

    And for your server, you can use SSL Server Test (Powered by Qualys SSL Labs) and SSL Security Test | ImmuniWeb.

    You may need to adjust your SSL settings, update your SSL certificates, or contact your hosting provider or network administrator for assistance.

    ERR_SSL_OBSOLETE_VERSION

    This error happens when the website is using an outdated or insecure version of SSL that is no longer supported by the browser. This could happen if the website has not updated its SSL configuration to use the latest standards, such as TLS 1.2 or 1.3.

    To fix this error, you need to update your SSL configuration to use the most secure and up-to-date version of SSL that is compatible with all major browsers. You may also need to update your SSL certificates or contact your hosting provider for assistance.

    ERR_SLL_PROTOCOL_ERROR

    This error means that there is a problem with the SSL protocol used by the website. This could happen due to various reasons, such as incorrect SSL settings, corrupted SSL certificates, or malicious interference by third parties.

    To fix this error, you need to check your SSL settings and make sure that they are correct and consistent. You may also need to clear your browser’s cache and cookies, disable any extensions or VPNs that may interfere with the SSL connection, or scan your device for malware or viruses.

    Mixed Content Error

    If the website is loading some resources over HTTP instead of loading everything over HTTPS, it could compromise the security of the page. This could happen if the website has not updated its links, images, scripts, or other elements to use HTTPS URLs.

    To fix this error, you need to make sure that all the resources on your website are loaded over HTTPS. You can use tools such as Why No Padlock? or SSL Check to find and fix mixed content issues on your website.

    Expired SSL Certificate

    SSL certificates are not permanent, and you will need to re-issue them before their expiry date. This error occurs when the SSL certificate for the website has expired and is no longer valid. This could happen if the website owner has forgotten to renew the certificate before its expiration date, or if there are delays or errors in the renewal process.

    To fix this error, you need to renew your SSL certificate as soon as possible and install it on your server. You may also need to contact your CA or hosting provider for assistance.

    Conclusion

    In today’s digital landscapе, SSL certificates are more than just a checkbox for sеcurity; thеy are a cornerstone of online trust and user safеty – maintain your SSL cеrtificatеs for a sеamlеss, sеcurе onlinе еxpеriеncе.

    We hope this article helps you resolve any SSL issues on your website and improve your web security. If you have any questions or feedback, please feel free to leave a comment below.

    If you are looking for a simple and powerful way to manage your cloud servers and install SSL certificates, you should try RunCloud.

    RunCloud is a cloud server management panel that lets you host multiple web applications and websites with fast and easy configuration. You can also install, configure, and remove SSL certificates with one click, thanks to RunCloud’s integration with Let’s Encrypt.With RunCloud, you don’t need to be a Linux expert or deal with complex commands to secure your website with SSL. Start using RunCloud today!

  • How To Check & Upgrade Your WordPress Version

    How To Check & Upgrade Your WordPress Version

    WordPress is a popular and powerful content management system that powers millions of websites around the world. For that reason, and to ensure security, compatibility, and performance remain excellent, official updates are released on a regular basis.

    This is why keeping your WordPress version up to date is crucial for the security, performance, and functionality of your site.

    In this article, we will show you how to check your WordPress version using various methods, and how to upgrade your WordPress version using different options.

    How to Check Your WordPress Version

    There are several ways to check your WordPress version, depending on your level of access and preference. Here are some of the most common methods:

    • Check the WordPress dashboard: The easiest way to check your WordPress version is to log in to your WordPress dashboard and look at the bottom right corner of the screen. You will see a message that says “Thank you for creating with WordPress”, followed by the version number.
    WordPress dashboard version
    • Check the source code of your website: Another way to check your WordPress version is to view the source code of your website in your browser. You can do this by right-clicking on any page of your website and selecting “View page source”.

      Then, look for a line that starts with <meta name="generator" content="WordPress ..." The content attribute will show you the WordPress version.
    • Check the wp-includes/version.php file: Another method to check your WordPress version is to access the wp-includes/version.php file in your WordPress root directory. You can do this by using an FTP client or a file manager tool in your hosting control panel. You will see a file that contains several
      PHP variables, one of which is $wp_version. The value of this variable is your WordPress version.If you have SSH access to your server, you can execute the following command in the root directory of your WordPress folder to see only the relevant lines instead of opening the entire text file.
    grep "wp_version" wp-includes/version.php
    check wordpress version
    • Use WP-CLI: Another way to check your WordPress version is to use the command-line interface (CLI) if you have SSH access to your server. To check your WordPress version, you need to navigate to your WordPress root directory, where the wp-config.php file is located, then, run the following command to check your WordPress version:
    wp core version

    How to Upgrade Your WordPress Version

    Once you know your WordPress version, you may want to upgrade it to the latest version available. There are several benefits of upgrading your WordPress version, such as:

    • Improved security: Upgrading your WordPress version will protect your site from potential vulnerabilities and attacks that may exploit outdated code.
    • Improved performance: Upgrading your WordPress version will enhance the speed and efficiency of your site, as newer versions often include optimizations and bug fixes.
    • Improved functionality: Upgrading your WordPress version will enable you to use new features and functionalities that may not be compatible with older versions.

    Before updating anything, it is always recommended to back up your site, including your files and database, in case something goes wrong during the update process.

    There are different ways to upgrade your WordPress version, depending on your preference and situation. Here are some of the most common methods:

    Use the Automatic Update Feature

    The easiest way to upgrade your WordPress version is to use the automatic update feature that is built into WordPress. You can do this by logging in to your WordPress dashboard and clicking on “Updates” in the left sidebar.

    You will see a message that tells you if there is a new version available, and a button that says “Update Now“. Clicking on this button will initiate the update process, which may take a few minutes.

    Use the Manual Update Method

    Another way to upgrade your WordPress version is to use the manual update method.

    To update WordPress using the command-line interface (CLI), you can use the wp core update command, which updates WordPress to the latest stable version. You can also use some options to customize the update process, such as:

    • You can specify the zip file to use, instead of downloading from wordpress.org. For example, if you have a zip file named wordpress-6.3.0.zip in your current directory, you can run:
    wp core update wordpress-6.3.0.zip
    • You can use the –minor flag to only install updates for minor releases, such as updating from WP 6.3 to 6.3.3 instead of 6.4.2. For example, if you want to update to the latest minor version, you can run:
    wp core update --minor
    • You can specify the WordPress version using –version flag to update to a specific version, instead of to the latest version. You can also use nightly to update to the latest development version. For example, you can run:
    wp core update --version=6.3
    wp core update --version=nightly
    upgrade wordpress via cli
    • When the installed WP version is greater than the requested version, you need to specify –force flag. This can be useful if you want to downgrade your WordPress version for some reason. For example, if you want to downgrade from WP 6.3 to WP 6.2, you can run:
    wp core update --version=6.2 --force
    • By default, WordPress uses English. However you can specify the –locale option to select which language you want to download. For example, if you want to download the French version of WordPress, you can run:
    wp core update --locale=fr_FR

    Note: If you see “Error: Another update is currently in progress”, you may need to run wp option delete core_updater.lock after verifying that another update isn’t actually running.

    Final Thoughts

    Updating your WordPress version is essential for the security, performance, and functionality of your site. You should always keep your WordPress version up to date with the latest version available, or at least with the latest minor version.

    In this article, we have shown you how to check and upgrade your WordPress version using various methods. We also explored how to use the command-line interface (CLI) to check and update your WordPress version.

    If you are looking for an easy and convenient way to get started with WordPress, you should check out RunCloud. RunCloud is a cloud-based platform that allows you to manage your WordPress sites on any cloud server.

    With RunCloud, you can easily install, update, backup, restore, clone, migrate, and secure your WordPress sites with just a few clicks. Sign up for RunCloud today!

  • The Easiest Way To Automate WordPress Deployments with Git

    The Easiest Way To Automate WordPress Deployments with Git

    WordPress is the most popular content management system on the web, with a CMS market share of 64.3%, and powering over 35 million websites around the world.

    Keeping track of a large WordPress site can be a complex and time-consuming process. However, by using Git, a version control software, developers can streamline their workflow.

    Git has become an integral part of modern web development, with 93% of developers using it in their projects, according to a recent survey by Stack Overflow.

    By leveraging the power of Git with tools such as RunCloud, developers can simplify the deployment process, reduce the risk of errors, and save both time and resources.

    Whether you’re a freelance developer or part of a larger team, automating your WordPress deployments with Git is a smart and efficient choice.

    In this article, we will show you how to use RunCloud’s Automatic Deployment functionality to create a streamlined workflow.

    Note: Before we get started, make sure you have a website stored on one of the supported git providers, and a server connected to RunCloud.

    Creating A Web Application

    You’ll need to clone your website to RunCloud before we can configure automatic deployments. To do this, go to your RunCloud dashboard and switch over to the “Git Repository” tab and select the git provider where your code is hosted.

    Give your application a suitable name, and select whether you want to use an existing user or create a new one.

    Note: if you plan to host multiple git repositories, you will need to have a separate owner for each repository, otherwise you will get a “Key already in use” error at a later stage.

    Next you will need to specify the domain name that you want to use. If you don’t have a domain yet but want to follow along with this tutorial, you can use the test domain provided by RunCloud.

    After specifying the domain name, scroll down to the git section. In the Repository field, enter your git username, followed by a “/”, and then the name of the repository.

    In the Branch field, enter the name of the branch that you want to deploy. For example, if the URL of your repository is “https://github.com/tatticoder/my-wp-site” then you need to enter “tatticoder/my-wp-site” in the repository field.

    Next, you’ll need to configure the deployment key. If you don’t have a deployment key, click on “Generate key” and it will generate a new key for your current user. You’ll then need to add the deployment key of this RunCloud user to your git server.

    This is a straightforward process. Go to your git repository and open the “Settings” tab. Look for the “DeploymentKeys” menu and click on “Addkey”. Now paste the key that was shown in RunCloud dashboard and click “Save”.

    After you have added the key, you should see it in your git dashboard. Now, you can go back to the RunCloud dashboard and continue the rest of the setup.

    You can specify where you want to automatically backup your site or select the PHP version that you want to use.

    Once you have made all the necessary changes, click on “Deploy” to finish the setup.

    Configuring Atomic Deployment on RunCloud

    After adding the web application to your server, you can take advantage of RunCloud’s Atomic Deployment functionality. This streamlines your website management process, and automatically updates your website whenever you push a commit to git repository.

    To configure Atomic deployment, go to RunCloud dashboard and look for “Atomic Deployment” in the left submenu. Now, click on “Add New Project” to get started.

    The setup process is super simple, and takes only a couple of seconds – you only need to provide a descriptive name for the project and specify the application that you want to deploy. Once you click “Save”, your web application will be converted to use Atomic deployment.

    Note: The dropdown menu will only list web applications that are currently deployed on your server via git. If you don’t see your application in the list, make sure you completed the creating a web application step successfully.

    After you have created a web application project, you will need to add a Webhook to your git server – this notifies RunCloud when a change has been made to your application.

    To configure a webhook, open the “Project info” page in RunCloud – you will see a webhook URL. Copy that URL and go to your git server. Open the “Settings” tab of your repository and look for the “Webhooks” menu.

    In the webhook section, create a new webhook, and paste the URL that we copied earlier into the payload URL field. Change the content type to “application/json” and make sure that push event will trigger the webhook. Click on “Add” to finish the setup.

    Testing the Deployment

    Once you have added the webhook, RunCloud will be notified about any changes made to your web application, and will automatically update the live website.

    To test this, make a small change to your website. Once you commit and push the changes to the right branch, it will trigger a webhook event.

    You can verify whether this event was successful by hovering over the webhook URL on your git server:

    When an event is delivered to RunCloud, the Atomic deployment will automatically fetch all the new changes, try to build a new copy of the website, and publish it on the server.

    You can see the number of failed and successful deployments in the Atomic Deployments dashboard:

    If a deployment is failing for any reason, you can see its build logs by clicking on the name of the deployment, and use these to identify which step is failing – and act accordingly.

    Conclusion

    Using Git to automate WordPress deployments saves time and allows multiple developers to work on the same codebase. RunCloud’s Atomic Deployment functionality simplifies the deployment process by automatically pushing the changes to the live server –reducing the risk of errors and downtime.

    If you’re tired of managing your own servers – you might want to check out RunCloud (yep, that’s us!). RunCloud is built for developers that want to focus on shipping great work, not on managing their infrastructure.

    Discover what a painless server configuration feels like, allowing you to avoid having to spend hours figuring it out. Get started with RunCloud today, and get up and running in minutes.

  • Self-Managed or Managed Hosting: Which One is Right for You?

    Self-Managed or Managed Hosting: Which One is Right for You?

    Choosing a hosting plan for your website or application can be a daunting task. There are so many options and factors to consider, such as cost, performance, security, scalability, support, etc.

    How do you know which one is the best for your needs and budget?

    In this article, we will explain the pros and cons of two common types of hosting: self-managed and managed hosting.

    We will also introduce you to a better solution that combines the advantages of both: RunCloud.

    Read on to find out more about self-managed vs managed hosting and how RunCloud can help you with your web hosting needs.

    Self-Managed Hosting

    Self-Managed Hosting, sometimes also known as self-hosted WordPress, is a setup whereby a website runs on a web server that the user chooses and pays for. A self-hosted WordPress website gives the user more control and flexibility over their website, but also more responsibility for managing and maintaining it.

    To create a self-hosted WordPress website, you will need to:

    • Buy a domain name from a domain registrar
    • Get a hosting account from a suitable cloud provider
    • Configure DNS records
    • Manage SSL certificates
    • Periodically check for new updates or vulnerabilities in plugins or themes.

    These are the basic steps to create a self-hosted WordPress website.

    Pros of Self-Managed Hosting

    • Lower cost: Self-managed hosting is usually cheaper than managed hosting because the customer doesn’t have to pay for the additional services and features that the hosting provider offers.
    • More control: Managing hosting often gives the customer more control over the server and its configuration. The customer can customize the server according to their needs and preferences. They can also install any software or application that they want on the server.
    • Flexibility: This hosting allows the customer to change or upgrade the server as they wish. They can also scale the server resources up or down, depending on the demand and traffic of their website or application.
    • Customization: Customers can tailor the server to their specific requirements and goals. They can optimize the server for either performance, security, or functionality.

    Challenges of Self-Managed Hosting

    • Technical skills: Self-managed hosting requires you to have technical skills and knowledge to manage and maintain the server. You will have to deal with complex tasks such as installation, monitoring, and troubleshooting. You also have to be familiar with the underlying operating system and the software that you use on the server.
    • Security: When choosing this option, you might be faced with more security risks because you are responsible for securing the server and its data. You must implement security measures such as firewalls, antivirus software, encryption, authentication, etc., and then continually monitor the server for any potential threats or attacks.
    • Maintenance: Self-managed hosting demands more time and effort to keep the server running smoothly and efficiently. You need to perform regular maintenance tasks such as backups, updates, patches, etc.
    • Support: If you host your website yourself, you won’t get any support from the hosting provider. You must rely on your own skills and resources to solve any problems or challenges that you might face on the server. The hosting provider may only offer basic support, or charge extra fees for advanced support.

    Managed Hosting

    Managed hosting is a type of hosting where the hosting provider takes care of most of the server management and maintenance tasks, such as installation, updates, security, backups, monitoring, and support. The customer only has to focus on their website or application and its content.

    The hosting provider also provides additional features and services, such as performance optimization, scalability, load balancing, caching, etc. The customer has less control over the server and its configuration, but also less hassle and risk.

    Benefits of Managed Hosting

    • Higher performance: Managed hosting providers work with thousands of websites, and often optimize servers for speed and efficiency. The hosting provider also uses advanced technologies such as caching, load balancing, CDN, etc. to improve the loading time and responsiveness of the websites or applications.
    • Reliability: Managed hosting provides more reliability than self-managed hosting because the hosting provider monitors the server for any issues or errors – and fixes them promptly.
    • Security: The hosting providers often work with a team of security experts that implements security measures such as firewalls, antivirus software, encryption, authentication, etc.
    • Support: You can easily get 24/7 technical support by contacting the hosting provider via phone, email, chat, ticket system, etc. Good hosting providers also provide documentation and tutorials to help the customer with their website or application.

    Drawbacks of Managed Hosting

    • Higher cost: Managed hosting is more expensive than self-managed hosting because the customer has to pay for the additional services and features that the hosting provider offers. The customer may also have to pay extra fees for exceeding limits or using additional resources on their plan.
    • Less control: You will get less control over the server and its configuration than self-managed hosting. You must also follow the rules and restrictions that the hosting provider sets for their plan.
    • Vendor lock-in: This is one of the major problems with managed hosting. A lot of hosting providers try to “vendor lock-in” the customer by forcing them to use a proprietary solution for their website.

    This is concerning because you may face difficulties in the future should the company remove a certain feature or change the pricing plans. Increase in hosting costs might tempt you to switch to another hosting provider but then you will lose some features or functionality that are specific to their current hosting provider or plan.

    • Compatibility issues: Managed hosting may cause compatibility issues for the customer because they have to use the software or applications that are compatible with their hosting provider or plan. The customer may not be able to use some software or applications that they want on their website or application.

    For example, If you rely on a legacy version of PHP for a certain application and the vendor chooses to phase that out, then your options are limited. You may have to update your plugin or find an alternative one that works with the newer version of PHP. In either case, you will need to solve a problem that was created by your hosting company.

    RunCloud: The Best of Both Worlds

    If you are fretting over which hosting option to choose, then worry not – RunCloud brings you the best of both worlds.

    RunCloud is a platform that lets you host any web application on your own server, whether it’s on a cloud provider or a private datacenter.RunCloud gives you the benefits of a managed service without the drawbacks of vendor dependency.

    With RunCloud, you can instantly deploy new WordPress websites with a few clicks, update DNS records with Cloudflare integration, and enable page caching with the RunCloud Hub plugin.

    You can also choose from different server types, such as Nginx+Apache, OpenLiteSpeed, or Docker. Furthermore, you can use the HTTP/3 protocol on your websites for faster loading.

    RunCloud provides you complete access to your server, application, database, and even underlying operating system at all times – there is no vendor lock-in. You can also back up your applications to any storage location you prefer, such as AWS S3, DigitalOcean Spaces, SFTP storage, etc.

    RunCloud is user-friendly: you can manage your servers from a dashboard without needing Linux skills. But you also have the option to log in to your server via SSH as the root user to customize your server settings if you want. You can also use the Developer API to control your servers programmatically.

    RunCloud ensures that your server and web application are secure and protected from any threats or attacks. We automatically update your server and apply security patches to keep it up to date and safe.

    RunCloud also has a built-in firewall and configures Fail2Ban on your server to block automated attacks. Best of all, you can configure Slack, email, and Telegram notifications for key actions on your server – such as ssh login, backup failure, etc., ensuring you stay informed and alert.

    Final Thoughts

    In this article, we have explained the pros and cons of self-managed and managed hosting for your website or application. Here are some recommendations or tips for choosing a hosting plan that suits your needs and budget:

    • Consider the type and size of your website or application, the traffic volume and growth rate, and the features and functionality required. These factors will determine the amount of server resources and services that you need.
    • Compare the cost of different hosting plans based on the criteria such as storage space, bandwidth, CPU cores, RAM, backups, SSL certificates, domains, etc.
    • Weigh the benefits and drawbacks of each hosting option in terms of performance, reliability, security, scalability, and support. You can use lists or bullet points to summarize the pros and cons of each option.

    Givе RunCloud a tеst drivе and discovеr its capabilities in meeting your web hosting requirements. RunCloud lets you to еffortlеssly host any wеb application on your sеlf-ownеd sеrvеr, whеthеr it’s hostеd by a cloud providеr or within a private datacenter.With RunCloud, you gain the advantages of a managed sеrvicе while avoiding the limitations of vendor rеliancе. Sign up for RunCloud today!

  • Mastering the Echo Command in Linux (with Practical Examples)

    Mastering the Echo Command in Linux (with Practical Examples)

    The echo command is one of the most basic and frequently used commands in Linux. It’s used to print text, variables, and special characters to the standard output, which is usually the terminal.

    However, the echo command can do much more than just printing text.

    It can also be used to create files and directories, test and debug scripts and commands, format and display messages, and generate output for other commands or programs.

    In this article we’ll show you how to use the echo command in Linux with some practical examples. We will cover the basic syntax of the echo command, as well as some of its options and features.

    By the end of this article, you will have a better understanding of how to use the echo command in Linux effectively and efficiently.

    What is the echo Command?

    The echo command is a way to communicate with your Linux terminal. It allows you to send text, variables, and special characters to the standard output, which is usually the terminal screen.

    The echo command is like a messenger that delivers your words to the terminal. It’s a simple but powerful tool that can be used for various purposes, such as:

    • Printing text, variables, and special characters to the standard output (e.g., terminal, file, or pipe).
    • Creating files and directories with specific content.
    • Testing and debugging scripts and commands.
    • Formatting and displaying messages, prompts, and menus.
    • Generating output for other commands or programs.

    How to Use the echo Command

    Here are some ways of using the echo command in Linux.

    Hello World!

    To send a text message to the standard output stream, use the echo command with a string argument enclosed in double quotes.

    For example, echo “Hello, world!” will write the string “Hello, world!” followed by a newline character to the standard output.

    Display Variable

    The command echo “$variable” is used to print the value of a variable to the standard output. A variable is a name that represents some data stored in the memory. The $ symbol is used to access the value of a variable.

    For example, $USER is a predefined variable that holds the name of the current user. To print the value of $USER, use echo “$USER”. This will display the current user name on the terminal screen.

    The command echo “\n” is used to print a special character to the standard output. A special character is a non-printable character that has some effect on the output, such as moving the cursor, clearing the screen, or making a sound.

    The \ symbol is used to escape the special character, which means to treat it as a literal character instead of its usual meaning. For example, \n is a special character that represents a newline, which moves the cursor to the next line. To print a newline character, use echo “\n”. This will output a blank line on the terminal screen.

    There are many other special characters that can be printed with the echo command, such as:

    • \t: A horizontal tab, which moves the cursor to the next tab stop.
    • \v: A vertical tab, which moves the cursor down one line and to the same column.
    • \a: An alert, which makes a beep sound.
    • \b: A backspace, which moves the cursor back one space.
    • \r: A carriage return, which moves the cursor to the beginning of the line.
    • \c: A control character, which suppresses any further output.

    You can see the full list of special characters by running man echo on your terminal.

    Writing to a File

    One of the lesser known functionalities of the echo command is redirecting the output from terminal into files. You can use the echo “content” > file command to create a file with some content to the standard output.

    The > symbol is used to redirect the output of the echo command to a file instead of the terminal screen. The file is the name of the file to be created or overwritten. The content is the text to be written to the file.

    For example, echo “This is a test file” > test.txt will create a file named “test.txt” with the text “This is a test file”. If the file already exists, it will be replaced by the new content. If the file does not exist, it will be created.

    If you want to append content to the end of an existing file, you can use the >> symbol instead of the > symbol. The >> symbol will redirect the output of the echo command to the end of the file without deleting the previous content.

    For example, echo “This is another line” >> test.txt will add the text “This is another line” to the end of the test.txt file, without erasing the text “This is a test file”. This way, you can add more content to a file without losing the original content.

    Writing to Both Terminal and File

    You might encounter cases where you need to display content in the terminal and store it in a file as well. In this case, you can use the echo “content” | tee file command to create a file with some content to the standard output.

    The | symbol is used to pipe the output of the echo command to another command, which is tee in this case. The tee command is used to write the input to both the standard output and a file or files. The file is the path of the file to be created or overwritten. The content is the text to be written to the file and displayed on the terminal screen.

    Debug Dynamic Commands

    If you are executing dangerous commands in the terminal, then it can go very bad, very quickly.

    The rm -rf * command will delete all files and directories in the current working directory recursively and forcefully with a single key press. This is a very dangerous command that can cause irreversible data loss.

    By using echo before the command, you can see what files and directories will be deleted without actually deleting them.

    The command echo rm -rf * is a way to check how the command rm -rf * will be composed without actually executing it. The echo command will print the command or script to the standard output, which is usually the terminal screen. This can help you avoid mistakes and errors.

    For example, if you want to delete all the files in the current directory that start with a certain prefix, you can do so using the following command.

    echo rm -rf <prefix>*
    Bash echo rm command

    In the above example we can see that our current directory has a total of 10 files, but since we used a prefix, only the files which matched the pattern were listed in the output. Once you are sure that this is the command that you want to execute, you can remove the echo from the beginning of the command and execute it as you normally would.

    Show Formatted Text

    The echo command is often considered a boring and simple command that only prints plain text to the terminal. However, this is not true. You can jazz up your output with a dash of color and style by using some special characters and options.

    Let’s see how to make your terminal more colorful and attractive with the echo command with the help of an example:

    • The -e flag in echo is used to enable the interpretation of special characters, such as \e, which are used to create colors and effects.
    • The \e[1;37;41m part is used to set the style, color, and background of the text. The \e symbol indicates the start of an escape sequence, which is a way to control the terminal behavior. The [ symbol indicates the start of a parameter list, which consists of numbers separated by semicolons. The m symbol indicates the end of the escape sequence. The numbers in the parameter list have different meanings, such as:
      • 1: This means to make the text bold.
      • 37: This means to set the foreground color (the color of the text) to white. The color codes range from 30 to 37 for standard colors, and from 90 to 97 for bright colors.
      • 41: This means to set the background color (the color behind the text) to red. The background color codes range from 40 to 47 for standard colors, and from 100 to 107 for bright colors.
    • After this, you can enter the text to be printed with the specified style, color, and background.
    • The \e[0m part is used to reset the style, color, and background of the text to the default values. The \e symbol indicates the start of an escape sequence, and the [0m part indicates the end of the escape sequence with a parameter of zero, which means to reset all attributes.

    Therefore, the command echo -e "\e[1;37;41mThis is white text on red background\e[0m" will print “This is white text on red background” in bold white letters on a red background, and then reset the terminal settings to normal.

    Some more ideas of displaying pretty output in terminal with the echo command are:

    • To display a message with an underline, use \e[4m. For example, echo -e "\e[4mThis is underlined text\e[0m" will print “This is underlined text” with an underline.
    • To display a message with a blinking effect, use \e[5m. For example, echo -e "\e[5mThis is blinking text\e[0m" will print “This is blinking text” with a blinking effect.
    • To display a message with different colors on each word, use \e[colorm before each word. For example, echo -e "\e[31mThis \e[32mis \e[33ma \e[34mrainbow \e[35mtext\e[0m" will print “This is a rainbow text” with different colors for each word.
    colorful output in bash echo command

    You can combine different styles and colors to create more interesting and attractive output in your terminal. However, you should also be aware that not all terminals support these features, and some may display them differently.

    You can see the list of available colors and styles by running man console_codes on your terminal.

    Execute Other Commands

    In a previous section, we discussed how echo can be used to debug commands without executing them. Now let’s see how it can be used to execute commands in bash.

    We know that the date command is a Linux utility that displays the current date and time. We can use it along with the echo command to print the output of the date command as a string, and format it accordingly.

    The command echo $(date) will print the current date and time to the standard output. The $(date) part is an example of command substitution, which is a way to execute a command and replace it with its output. For example, if you run echo -e "It is \e[1;31m$(date)\e[0m today.", you might see something like this:

    We already briefly mentioned in one of the previous sections that the | operator can be used to redirect output from the first command to the other.

    For example, the echo "Hello" | wc -c command can be used to print the number of characters in “Hello” to the standard output. The “Hello” part is a string argument for the echo command. The | symbol is used to pipe the output of the echo command to another command, which is wc -c in this case.

    The wc -c command is used to count the number of bytes in the input. The echo command will send the string “Hello” to the standard input of the wc -c command, which will count the number of bytes in “Hello” and print it as a number. Note that the number 6 includes the newline character that the echo command adds by default. If you want to exclude the newline character, you can use the -n option for the echo command, which will suppress the newline. For example, if you run echo -n "Hello" | wc -c, you will see something like this:

    echo command bash

    As you can see, using the echo command with command substitution or pipes can help you generate output for other commands or programs that can process or display it. You can use this technique to create dynamic and interactive output in your terminal.

    When Not to Use the echo Command

    The echo command is a great tool for printing simple text messages to the terminal, but it has its limitations. Sometimes, you may need to print data that is more complex, structured, binary, or more sensitive than plain text. In these cases, the echo command may not be suitable, and you may want to use other tools that are more specialized and secure.

    Here are some examples of such cases, and the tools you can use instead of the echo command:

    • If you need to print complex or structured data, such as JSON, XML, or tables, the echo command may not be able to preserve the formatting and indentation of the data. You may want to use tools such as jq, xmllint, or column, which can parse and pretty-print JSON, XML, or tabular data respectively.
    • If you need to print binary data, such as images, audio, or video, the echo command may not be able to display them properly in the terminal. You may want to use tools such as cat, hexdump, or base64, which can output binary data as raw bytes, hexadecimal numbers, or base64-encoded strings respectively.
    • If you need to print sensitive or confidential information, such as passwords, keys, or tokens, the echo command may not be able to protect them from being exposed or intercepted. You may want to use tools such as gpg or openssl, which can encrypt and decrypt data using various algorithms and keys.

    As you can see, there are many alternatives to the echo command that can handle different types of data more effectively and securely. You can choose the best tool for your needs depending on the nature and format of your data.

    After Action Report

    We hope you enjoyed this article and learned something new about the echo command in Linux. The echo command is a versatile and useful tool that can help you create and communicate with your Linux environment. Feel free to experiment with it and discover its potential!

    We would love to hear from you about your own use cases of the echo command. How do you use it in your daily tasks? What are some of the creative and fun ways you have used it? Please share your thoughts and experiences in the comment section below. We appreciate your feedback and suggestions!

    We understand that Linux can be intimidating for some people, especially if they are not familiar with the terminal. That’s why we recommend RunCloud as the best platform to manage your Linux servers. RunCloud provides a helpful dashboard that lets you easily deploy and manage your servers, applications, and websites without messing with the terminal.

    However, if you want to tinker under the hood, RunCloud also gives you the freedom and flexibility to access and customize your server settings via SSH or SFTP. RunCloud is the perfect solution for both beginners and experts who want to get the most out of their Linux servers.

    If you want to experience RunCloud for yourself, you can sign up for RunCloud and enjoy a 14-day, risk-free trial.

  • Introduction to Bash For Loops: A Beginner’s Guide

    Introduction to Bash For Loops: A Beginner’s Guide

    If you’re new to the command line and Linux, fear not! You don’t need to be a Linux expert to start using the power of the terminal.

    In this article, we’ll demystify the ‘for’ loop in Bash scripting. Whether you’re a developer, sysadmin, or just curious about the command line, understanding ‘for’ loops is essential.

    Why Are ‘For’ Loops Necessary?

    The ‘for’ loop is a fundamental construct that allows you to repeat a set of commands or actions multiple times. It’s like having a trusty assistant who diligently performs a task for you over and over again. Whether you’re processing files, managing directories, or automating tasks, there are many scenarios when loops are useful:

    1. File Processing and Batch Operations:
      • Loop through files in a directory to perform batch operations, such as renaming, moving, or compressing them.
      • Process log files, extract relevant information, and generate reports.
    2. System Administration and Configuration:
      • Iterate over a list of user accounts to apply changes (e.g., setting permissions, updating passwords).
      • Configure network interfaces, firewall rules, or services on multiple servers.
    3. Backup and Archiving:
      • Create backup scripts that loop through directories and files to archive or synchronize data.
      • Rotate log files by compressing older logs and keeping a specified number of recent ones.
    4. Automating Repetitive Tasks:
      • Run commands on multiple remote servers via SSH.
      • Schedule regular tasks (e.g., backups, database maintenance) using cron jobs.
    5. Data Processing and Transformation:
      • Parse CSV files or other structured data formats.
      • Transform data (e.g., converting file formats, extracting specific fields).

    Loops in general are versatile and can be adapted to various scenarios. They allow you to iterate over lists, directories, or any other collection of items in your scripts.

    In this post, we’ll explore the basic syntax of ‘for’ loops, and demonstrate their versatility with practical examples. By the end, you’ll be ready to wield this powerful tool in your Linux journey.


    Basic Syntax of Bash ‘For’ Loop

    A 'for' loop is a control structure in programming that allows you to repeat a set of commands for each item in a list. It’s like a conveyor belt that processes each item one by one.

    Syntax:

    • for variable in list: This line initializes a loop. The variable represents the current item from the list.
    • do: This marks the beginning of the loop body.
    • # Commands to execute for each item in the list: Here, you can put any commands or actions you want to perform on each item.
    • done: This marks the end of the loop.
    for variable in list
    do
        # Commands to execute for each item in the list
    done

    Explanation:

    • You define a variable (usually a single letter) to keep track of the current item.
    • The list contains multiple items (e.g., filenames, numbers, or strings).
    • For each item in the list, the commands inside the loop are executed.
    • Once all items are processed, the loop ends.

    Execution Frequency:

    • The for loop executes once for each item in the specified list.
    • If there are n items in the list, the loop will run n times.
    • For example, if you have a list of three filenames (file1.txt, file2.txt, and file3.txt), the loop will execute three times, once for each filename.
    for filename in file1.txt file2.txt file3.txt
    do
        if [ "$filename" == "file2.txt" ]; then
            echo "Found file2.txt! Exiting loop."
            break
        fi
        echo "Processing $filename"
    done
    bash for loops

    Using Bash ‘For’ Loop

    Looping through Files and Directories

    You can use a 'for' loop to process files or directories. This is ideal if you want to traverse through a directory which has a large number of files, or if the number of files keep changing.

    #!/bin/bash
    for file in /path/to/files/*; do
        echo "Processing file: $file"
        # Add your custom commands here
    done
    bash for loop file processing

    Iterating over a Range of Numbers

    To loop through a range of numbers, use the {start..end} notation. If you want to run the loop a fixed number of times, you can create a list of numbers using this format.

    #!/bin/bash
    for i in {1..5}; do
        echo "Number: $i"
    done
    number list in for loop

    Using ‘for’ with Command Substitution

    The ‘for’ loop is flexible and powerful. You can redirect the output of other commands in the loop, and then process each item in the list.

    #!/bin/bash
    for user in $(cut -d: -f1 /etc/passwd); do
        echo "User: $user"
    done

    Nested ‘for’ Loops

    If a simple ‘for’ loop isn’t enough, you can use multiple ‘for’ loops together to achieve more complex functionality.

    #!/bin/bash
    for outer in A B C; do
        for inner in 1 2 3; do
            echo "$outer->$inner"
        done
    done

    Final Thoughts

    You’ve now unlocked the potential of Bash for loops. It is like a Swiss Army knife for your command line adventures. Mastering the ‘for’ loop opens up endless possibilities for automating tasks and managing data efficiently in your Linux environment.

    Remember, the command line need not be intimidating, but if you do find it a bit daunting then you should check out RunCloud, a web platform to manage your servers that works with any cloud provider. Sign up for RunCloud and experience the best of both worlds:

    • Web-Friendly Dashboard: Get started quickly without diving into complex Linux commands. RunCloud provides an intuitive interface for managing your servers.
    • Command Line Freedom: If you’re a terminal enthusiast, RunCloud gives you the flexibility to tinker with the command line whenever you wish.
  • Cloudflare R2 vs AWS S3 – Full Comparison

    Cloudflare R2 vs AWS S3 – Full Comparison

    Cloud storage is a vital service for developers who need to store and access large amounts of data on the cloud. However, choosing the right cloud storage provider can be challenging, as there are many factors to consider, such as pricing, performance, reliability, compatibility, and features.

    In this article, we will compare two popular cloud storage services: Cloudflare R2 and AWS S3. We will look at the similarities and differences between these two services in terms of their pricing, performance, reliability, compatibility, and features. Let’s get started!

    What Is AWS S3?

    AWS S3 is short for a simple storage solution, it is a cloud-based service that stores data. It lets you store and access any amount of data over the internet. Data is stored in buckets, you can create buckets to organize your data and control who can access it. Customers are charged a monthly fee for storing their data and a network fee for each time it is requested over the internet.

    S3 can be used to host static websites, backup files, archive data, and integrate with other AWS services. S3 is highly scalable, reliable, and secure – and above all, has a thriving ecosystem and community.

    AWS S3 hero image

    What is Cloudflare R2?

    Cloudflare R2 is a cloud storage service that lets you store and access data over the internet. The most attractive feature of this service is the absence of network egress fees. However, customers are still charged a monthly fee for storing their data, changing it, and reading it. It is compatible with the S3 API, which means you can use existing tools and libraries to work with your data.

    R2 can be integrated with Cloudflare Workers, a serverless platform that lets you run code at the edge. R2 is globally distributed and integrated with Cloudflare’s CDN, which makes it fast and reliable.

    Cloudflare R2 hero image

    Cloudflare R2 vs AWS S3: Features Comparison

    Storage Options

    Both Cloudflare R2 and AWS S3 do not have a limit on the amount of data that can be stored in a bucket. You can store as much data as you like. However, there is a limit on the size of individual objects. A single object can be a maximum of 5 TB, and to upload files larger than 5GB, you have to use the multipart upload process.

    AWS S3 offers a range of storage options for different use cases and performance requirements. The main storage options are:

    • S3 Standard: This is the default storage option for frequently accessed data. It is suitable for cloud applications, dynamic websites, content distribution, and big data analytics. The first 50 TB of data costs $0.023 per GB every month.
    • S3 Intelligent-Tiering: This is a storage option that automatically moves data to the most cost-effective access tier based on access frequency without performance impact or operational overhead. It is ideal for data with unknown or changing access patterns, such as long-lived data sets that are accessed infrequently but require rapid access when needed.

    It has a complex pricing structure – Frequent, Infrequent, and Archive Instant Access Tier are all priced differently, starting at $0.023, $0.0125, and $0.004 per GB per month. In addition to this, customers are also charged a monitoring and automation fee for objects greater than 128 KB which costs $0.0025 per 1,000 objects.

    • S3 Standard-Infrequent Access: This storage option is for less frequently accessed data that still needs to be available quickly when accessed. It is suitable for backups and disaster recovery. It costs $0.0125 per GB per month.
    • S3 One Zone-Infrequent Access: This is similar to the above option except that S3 Standard-IA stores data across multiple Availability Zones, while S3 One Zone-IA stores data in a single Availability Zone and has a lower cost. It is more suitable for re-creatable data that is not important. This storage class is priced at $0.01 per GB.
    • S3 Glacier Instant Retrieval, S3 Glacier Flexible Retrieval (formerly S3 Glacier), and S3 Glacier Deep Archive: These are storage options for archiving data that is rarely accessed and does not require immediate access. They offer different retrieval times and costs depending on the urgency of the data access. They are suitable for long-term archiving and digital preservation of data.
      For example, if you need to store a large number of logs for regulatory purposes, this is the right choice for it. Data stored in Instant Retrieval ($0.004/GB), Flexible Retrieval ($0.0036/GB), and Deep Archive ($0.00099/GB) can be accessed within a couple of milliseconds, or it can take up to 12 hours.
    • S3 Outposts: This is a storage option for storing S3 data on-premises using AWS infrastructure. This service extends AWS infrastructure and services to customer sites. It is suitable for data residency requirements that cannot be met by an existing AWS Region and costs tens of thousands of dollars per month.

    You can also use S3 Lifecycle policies to automatically transition objects between storage options. All the prices mentioned above are for the North Virginia region of AWS, the exact prices vary from region to region.

    Cloudflare R2 provides only one storage class and does not change prices based on location. The first ten GB of storage, ten million read operations and one million write operations are free every month. Beyond the free limit, you can pay $0.015/GB for storage, $0.36, and $4.50 for a million write and read operations, respectively.

    The buckets are created automatically in a region closest to you, you can suggest a suitable location for your bucket, but it is not guaranteed. The object life cycle feature (currently in beta) from Cloudflare can automatically delete objects that are older than a certain time period – this is great for reducing billing costs.

    Security

    Cloudflare R2 encrypts your data at rest – all objects stored in R2, including their metadata, are encrypted at rest using AES-256. The encryption keys are stored and managed by Cloudflare internally. In addition to this, Cloudflare adheres to industry-standard security compliance certifications, such as SOC 2 Type II, PCI DSS Level 1, ISO 27001/27002, GDPR, and CCPA.

    AWS S3 on the other hand offers far more flexibility. AWS S3 supports server-side encryption with three key management options: SSE-KMS, SSE-C, and SSE-S3, as well as client-side encryption. SSE-KMS allows you to use AWS Key Management Service (KMS) or your own customer master keys (CMKs) to encrypt your data. SSE-C allows you to provide your own encryption keys. SSE-S3 uses keys that are managed by S3 and protected by AWS KMS1. These options are not available in Cloudflare R2.

    Although both Cloudflare and AWS use TLS to encrypt your data in transit, AWS takes it one step further by offering AWS PrivateLink, a service to establish a private connection between your VPC and S3 – this transfers your data without exposing it to the internet.

    AWS S3 maintains compliance programs, such as PCI-DSS, HIPAA/HITECH, FedRAMP, EU Data Protection Directive, and FISMA, to help you meet regulatory requirements. AWS S3 also provides various mechanisms to control access to your data, such as AWS Identity and Access Management (IAM), Access Control Lists (ACLs), bucket policies, query string authentication, and pre-signed URLs.

    Data Migration

    AWS S3 provides various options for migrating data from different sources, such as on-premises systems, other cloud providers, or other S3-compatible services. You can either use online services such as AWS DataSync, AWS Direct Connect, AWS Transfer Family, etc. or physically move your data using offline services such as AWS Snowcone, AWS Snowball, and AWS Snowmobile.

    Cloudflare R2 on the other hand has a much less mature ecosystem. The only option to transfer data is by either using its Super Slurper service for one time migrations or Sippy for incremental data migration.

    Other Features

    Cloudflare R2 is still evolving and growing, it has a limited number of features that work well in certain environments. You can use it with Cloudflare Workers, a serverless runtime, to bind a bucket to a Worker and change objects on the fly as they go in or out of R2 storage buckets.

    AWS S3, on the other hand, offers a solution for all your requirements and offers many features that are not available on Cloudflare R2.

    AWS Marketplace

    AWS Marketplace for S3 allows you to explore and subscribe to third-party software products that are built for Amazon S3 from within the S3 Management Console. You can choose from various product types, such as SaaS, AMI, CFT, and containers.

    There are solutions available for many categories, such as Storage, backup and Recovery, Data Integration and Analytics, Observability and Monitoring, Threat Detection, and Permissions. The marketplace helps streamline the process of deploying software solutions that run on AWS.

    AWS S3 marketplace

    Bucket Versioning

    AWS S3 bucket versioning is a feature that allows you to keep multiple versions of an object in the same bucket. You can use bucket versioning to preserve and restore every version of an object stored in your bucket. This can help you recover objects from accidental deletion or overwriting.

    By default, your bucket is unversioned, which means that there is only one version of each object in the bucket. If you enable versioning for a bucket, AWS S3 automatically generates a unique version ID for each object that is stored or modified in the bucket.

    If you overwrite an object in a versioned bucket, AWS S3 adds a new version of the object in the bucket. The previous version remains in the bucket, you can still access and restore the previous version of the object if you need to.

    Object Locking

    Object locking in AWS S3 is a feature of versioned buckets that allows you to store objects using a write-once-read-many (WORM) model. This can help prevent objects from being deleted or overwritten for a fixed amount of time or indefinitely. It is useful if you need to meet regulatory requirements that require WORM storage or add an extra layer of protection against object changes and deletion.

    Object locking provides two retention modes: governance mode and compliance mode. These retention modes apply different levels of protection to your objects. In governance mode, users can’t overwrite or delete an object version or alter its lock settings unless they have special permissions. In compliance mode, a protected object version can’t be overwritten or deleted by any user, including the root user in your AWS account. When an object is locked in compliance mode, its retention mode can’t be changed, and its retention period can’t be shortened.

    Performance and Reliability

    Both Cloudflare and AWS are the titans of the cloud industry and boast 99.999999999% (eleven 9’s) of annual durability. This is very hard to interpret, let’s understand this with the help of an example. Imagine you have a big bucket of rice with one billion grains, if your bucket offered similar reliability then you will lose a maximum of one grain every year.

    Both cloud services are globally distributed, have redundancy built into their infrastructure, and offer a similar level of performance and reliability.

    Cost

    Cloudflare takes pride in its simple pricing plans. It offers a generous free tier, beyond which customers are charged $0.015 per GB of storage, $4.50 for million operations that change the state of the object, and $0.36 per million object reads every month. Cloudflare R2 does not charge any network egress fee.

    Cloudflare R2 purchase dashboard

    AWS, on the other hand, is infamous for its complex pricing structure. Even for experienced professionals, calculating your AWS bill is an arduous ordeal. You are charged separately for each storage class, you pay a fee for requests made against your buckets, and you pay for all bandwidth into and out of Amazon S3 (except in a few cases). There is an additional data retrieval fee for reading data from certain storage classes. Moreover, if you are using storage management features such as Amazon S3 Inventory, S3 Storage Class Analysis, etc. then you will be billed for them separately.

    You can use R2 Calculator and Amazon S3 calculator to calculate an estimate of your monthly bill. Let’s compare both services with the help of a few examples.

    Example 1

    Let us assume you store 10000 GB of data in a cloud bucket that is frequently accessed from North Virginia. You perform 5000000 write operations and 25000000 read operations every month. The above scenario will cost you $265 ($230 for storage, $25 for PUT requests, and $10 for GET requests) every month when using AWS S3 Standard. A similar solution will cost $173.25 per month on Cloudflare.

    If you are serving traffic to the internet, then AWS will also levy an outbound data transfer fee. If you transfer 10TB of data, you will be charged $921 per month. Cloudflare does not charge any network egress fee.

    In this scenario, if you use AWS S3, you will end up paying $1,186.60 ($265+$921) every month whereas if you use Cloudflare R2, you will only need to pay $174 per month.

    Example 2

    In this scenario, let’s assume you need to store 100000 GB of data that is seldom accessed. On AWS, there is a special storage class for such objects, S3 Glacier Deep Archive. If you perform 5000 write operations every month and a negligible amount of read requests and outbound data transfer, then your AWS bill will be approximately $100 whereas Cloudflare will charge you nearly $1500. 

    Related: Amazon Route 53 vs. Cloudflare DNS – Which Is Better?

    Final Thoughts

    Cloudflare R2 is a new and upcoming service. It has not fully matured yet and still has some room for improvement. It has lower prices than AWS S3 and can be a good option for delivering data on the web. However, it does not have all the features and flexibility offered by S3.

    In short: It’s a good option for some use cases – in fact, in some cases, even a great solution – but not to be considered a drop-in substitute for S3 and what it’s capable for (especially if you already use AWS for various other parts of your architecture.

    If you’re tired of managing your own servers – you might want to check out RunCloud (yep, that’s us!). RunCloud is built for developers that want to focus on shipping great work, not on managing their infrastructure. Painless server configuration, so you don’t need to spend hours figuring it out – get started with RunCloud today & get up and running in minutes.

  • How to Use LiteSpeed Cache on RunCloud Servers without a Plugin

    How to Use LiteSpeed Cache on RunCloud Servers without a Plugin

    LSCache is a built-in page caching feature of the OpenLiteSpeed web server that can significantly improve the speed and performance of your website by storing frequently accessed data in a cache.

    In this article, we’ll show you exactly how to use LSCache on RunCloud servers in web applications that don’t already have built-in LSCache support.

    Prerequisites

    Before you start, you’ll need to have the following:

    • A RunCloud account, and a connected server with the OpenLiteSpeed stack.
    • A web application installed on your server.

    How to Choose Between Public and Private Caching

    Caching is a technique that allows the web server to store frequently accessed data in a temporary storage area, called a cache. This can improve the speed and performance of the website by reducing the amount of time it takes for the server to process and retrieve the data when a user requests a page.

    What is Public Caching?

    Public caching, also known as shared caching, is when the cache is used by more than one client. For example, a reverse proxy or a gateway cache can act as a public cache for multiple users.

    Public caching can offer a greater performance gain and a much greater scalability gain, as a user may receive cached copies of web pages without ever having obtained a copy directly from the origin server themselves.

    For example, if you have a website that sells books, you might want to use public cache for the pages that show the book details, reviews, or categories. These pages are the same for all users, and so can be served from a public cache.

    What is Private Caching?

    A private cache, however, is only accessible to an individual visitor. It usually contains information that is only relevant to that particular user, such as the WordPress admin bar, the shopping cart, or their profile page. When a page is privately-cached, there is a separate, personalized copy stored for each user that requests it.

    For example, if you have a website that sells books, you might want to use a private cache for the pages that show the user’s order history, wishlist, or recommendations. These pages are different for each user, and so should not be served from a public cache.

    When to Use Public Caching, Private Caching, or No Caching

    Each particular URL of a website can be set up to be publicly cached, privately cached, or not cached at all, but cannot be both publicly and privatly cached at the same time. That is to say, you can only set up one cache type for a particular URL. Depending on the situation, you might want to set different URLs to be cached differently. The following outlines a few scenarios helpful in determining which type of caching should be used for a URL or a set of URLs.

    Use public caching for web pages that:

    • Do not change frequently.
    • Have high demand (requested frequently).
    • Are not sensitive or confidential.
    • Do not depend on who is looking at them.

    Use private caching for web pages that:

    • Can only be used by one user/client, such as personal information on a website (for authorized users).
    • Use resources such as documents that are only available for one particular user or authorized users.
    • Generates responses with cookies.

    Use no caching for web pages that:

    • Use a POST request.
    • Have dynamic content (such as time sensitive info).
    • Change frequently.
    • Should not be stored, such as the user’s payment details.

    How Cache Settings are Inherited and Overridden in LiteSpeed Servers

    Cache settings can be configured at different levels, such as server, virtual host, context, and script handler. The settings at each level affect how the cache works for the web pages under that level.

    Cache settings follow a general-to-specific hierarchy, and specific settings override general settings. This means that:

    • Cache settings at the server level apply to all web pages on the server, unless they are overridden by lower-level settings.
    • Cache settings at the virtual host level apply to all web pages under that virtual host (web application), unless they are overridden by lower-level settings.
    • Cache settings at the context level apply to all web pages under that context (location), unless they are overridden by lower-level settings.

    For example, if you enable public cache at the server level, but disable it at the virtual host level, then public cache will be disabled for all web pages under that virtual host.

    Enabling Caching

    To use LSCache on RunCloud servers, you need to do the following steps:

    1. Enable the LSCache Module at Server Level

    The first step is to enable the LSCache module on your OpenLiteSpeed server. You can do this by logging into the RunCloud dashboard, navigating to the server dashboard, and clicking on the “LiteSPeed” button in the left menu.

    Here, you can edit the module cache block and set the following settings at the server level:

    module cache {
      ls_enabled              1 # Enable LSCache module
      storagePath $VH_ROOT/lscache # Set the cache storage path
      checkPrivateCache   1 # Enable checking private cache
      checkPublicCache    1 # Enable checking public cache
      maxCacheObjSize     10000000 # Set the maximum cache object size in bytes
      maxStaleAge         200 # Set the maximum stale age in seconds
      qsCache             1 # Enable caching URIs with query strings
      reqCookieCache      1 # Enable caching requests with cookies
      respCookieCache     0 # Disable caching responses with Set-Cookie header
      ignoreReqCacheCtrl  0 # Respect the cache control settings in the request
      ignoreRespCacheCtrl 0 # Respect the cache control settings in the response
      enableCache         1 # Enable public cache
      expireInSeconds     3600 # expiration time for public cache in seconds
      enablePrivateCache  0 # Disable private cache
      privateExpireInSeconds 3600 # expiration time for private cache in seconds
    }

    You can also adjust other settings according to your preferences and needs, such as expireInSeconds, maxStaleAge, qsCache, etc. You can find more information about these settings in the OpenLiteSpeed documentation.

    After editing the module cache block, save the changes and restart the OpenLiteSpeed server.

    2. Configure Virtual Host-Level Cache Settings

    If you have more than one web application on your server, you may want to customize the cache settings for each virtual host. If you do not configure any cache settings at the virtual host level, then the cache settings at the server level will be inherited.

    To configure cache settings at the virtual host level, you need to add the cache module under each virtual host, and edit the OpenLiteSpeed config file to configure settings in the same way that you did at the server level.

    Using the .htaccess File

    An .htaccess file is a configuration file that allows you to override the server settings for a specific directory or web application. You can use our file manager tool on our panel to create and edit .htaccess files.

    1. Log in to the RunCloud panel and navigate to the file manager tool
    2. The next step is to locate the web app root folder of your web application. The web app root folder is the directory where your web application files are stored. For example, if your web application serves content from /public, then that is your web app root folder.
    3. Click the New File button and enter ‘.htaccess’ as the file name (including the full stop/period at the start of the filename).
    4. Finally, open the .htaccess file with the file manager tool and add rewrite rules. Rewrite rules are instructions that tell OpenLiteSpeed how to handle requests for certain URLs or conditions. You can use rewrite rules to enable or disable caching for specific URLs or web pages.

    To enable cache via .htaccess, you can add this script to the .htaccess file:

    <IfModule LiteSpeed>
    RewriteEngine On
    RewriteRule (.*\.php)?$ - [E=cache-control:max-age=120]
    </IfModule>

    This will cache all .php files on your web application for 120 seconds.

    To enable cache for your entire website except /private URL, you can try something like this:

    <IfModule LiteSpeed>
    RewriteEngine On
    ## cache should be available for HEAD or GET requests
    RewriteCond %{REQUEST_METHOD} ^HEAD|GET$
    # excluding certain URLs
    RewriteCond %{REQUEST_URI} !/(private)/$
    # cache for 2 mins for php pages only
    RewriteRule /(.*\.php)?$ - [E=Cache-Control:max-age=120]
    </IfModule>

    This will exclude /private URL from caching. You can use this to prevent caching of your admin panel.

    To enable private cache for sessions with cookies, you can write the config like this:

    <IfModule LiteSpeed>
    # for those not met above condition, enable private cache.
    RewriteCond %{REQUEST_METHOD} ^HEAD|GET$
    # excluding certain URLs
    RewriteCond %{REQUEST_URI} !/(private)/$
    ## select which pages to serve from private cache
    RewriteCond %{HTTP_COOKIE} !my-cookie=yes
    # private cache for however long set in cache policy for php pages only
    RewriteRule (.*\.php)?$ - [E=Cache-Control:max-age=120]
    RewriteRule (.*\.php)?$ - [E=Cache-Control:private]
    </IfModule>

    This will enable private cache for users who have a cookie named my-cookie stored on their computer, such as logged-in users or commenters.

    You can also use other rewrite conditions and flags to fine-tune your caching rules, such as checking for query strings, headers, etc. You can find more information about rewrite rules on the OpenLiteSpeed Knowledgebase.

    3. Test LSCache

    The final step is to test if LSCache is working properly on your web application. You can do this by using online tools such as LSCache Check or browser developer tools to check the response headers of your web pages.

    You can also use the following curl command to check the headers of a page.

    curl -I https://example.com/

    Executing the above command should give an output similar to the following screenshot:

    This means that OpenLiteSpeed has served a cached page from LSCache and has added a x-litespeed-cache header with a value of ‘hit’.

    Conclusion

    In this article, we have covered how to customize the LS Cache settings for each virtual host on OpenLiteSpeed, and how to use directives or rewrite rules in the .htaccess file of your virtual host. You can find more information about OpenLiteSPeed cache configuration on the official site.

    We hope this article was helpful and informative. If you have any questions or feedback, please feel free to leave a comment below.

    If you are looking for an easy and convenient way to manage your server, you may want to check out RunCloud. RunCloud is a cloud-based server management platform that allows you to deploy, configure, and monitor your web applications on any cloud provider.With RunCloud, you can easily install and update OpenLiteSpeed, LS Cache, and other web server components with just a few clicks. You can also enjoy features such as SSL certificates, backups, firewall, cron jobs, and more. Start using RunCloud today!