One place for hosting & domains

      Website

      How to Change Your Domain Without Hurting SEO and Losing Website Traffic


      If you’re a freelancer or a small business owner, chances are you’ve had to learn by doing. This works really well for many things (perhaps excluding rocket science).

      While this learn-as-you-go approach can take you far in the technical realm, it can occasionally have its downsides. For instance, changing your entire website domain, all your site’s URLs, all the organic history that comes along with it, may not be the best area to “wing it.” You risk causing substantial harm to your online presence.

      The good news is that you can change your domain name. And you can do so without permanently impacting your SEO. And we’ll show how to do it, right here in this post.

      What a deal!

      In this post, we’ll first cover a few reasons why you might change your domain name, as well as the potential SEO dangers of doing so. Then, we’ll show you how to modify your domain without damaging your site’s visibility. Let’s get started!

      Why You May Want to Change Your Domain Name (Common Reasons)

      For many website owners, choosing a domain name is one of the most important decisions they can make when crafting an online presence. While some may get lucky and select a domain that lasts a lifetime, it’s possible that your domain name needs changing at some point:

      searching for the right domain name

      Here are just a few reasons you might want to consider a domain change:

      • Rebranding. Many of the best online businesses will either evolve or pivot in order to succeed in the competitive e-commerce marketplace. You may need to update your domain name to reflect your site’s new image.
      • Copyright issues. Even the most well-intentioned entrepreneur can make a mistake. If you find out that your domain name is infringing on someone’s intellectual property, you will likely need to change it to prevent legal issues.
      • Growth. Your small business may need to modify its domain in order to expand. For example, if your old domain name is too specific, you might need to change it to something more general.
      • Relocation. If you run an online store, moving locations may not be a very big deal. However, if your domain has a country code Top-Level Domain (ccTLD) such as .us or .ca, you might need to modify it to avoid confusion.

      These are just a few common scenarios that may require you to register a new domain name. However, you might have other reasons. For instance, maybe you’ve been monitoring your ideal domain and found that it’s become available. There’s nothing wrong with upgrading simply because you’ve found something better.

      The (Avoidable) Dangers of Changing Your Domain Name

      If you’re considering changing your domain name, chances are you already know a bit about Search Engine Optimization (SEO). In a nutshell, SEO is when you make an intentional effort to get your pages to rank higher in Google’s search engine results. For most site owners and digital marketers, SEO and site performance are a top priority these days.

      Therefore, you’ve likely heard some horror stories about people changing their domain and losing all their hard-earned rankings. This type of loss can have serious consequences for any business. That’s because when your site is no longer visible, new visitors won’t be able to find it, and search engines won’t show it in search results.

      While this can happen, you don’t need to panic. As long as you follow SEO best practices and change your domain name the right way, you can avoid most of the damage to your search engine rankings. What’s more, you can even minimize other inconveniences, like unnecessary downtime.

      Get Content Delivered Straight to Your Inbox

      Subscribe to our blog and receive great content just like this delivered straight to your inbox.

      How to Change Your Domain Name Without Hurting SEO

      Now that you know some of the common motivations for modifying a domain name, and how it could affect your website, you’re probably wondering how to do it with minimal side effects. Here are five steps you can follow to change your domain name without damaging your site’s visibility.

      Step 1: Choose a New Domain Name with Lasting Power

      The first step is to simply choose a good domain name. For starters, you’ll want to pick a domain with an appropriate Top-Level Domain (TLD).

      It’s also a good idea to make your new domain easy to spell, type, and pronounce. That way, you can avoid visitors becoming frustrated by frequent typos. It will also encourage users to share your domain name verbally.

      You’ll also want to make sure that your new domain offers flexibility. This will help ensure that it can grow with your online business and avoid the need for another name change in the future.

      You may also want to use a more advanced tool, such as ahrefs Backlink Checker. This can further help you determine if a domain name is viable, or if you’d need to disavow unwanted backlinks in order to use it. Once you’re satisfied with your research, you can go ahead and buy your new domain name.

      Step 2: Audit Backlinks & Referring Domains

      Even though you’ve picked the right domain name, you’re not quite ready to make the switch yet. Before you make any sudden changes, you would be wise to conduct a thorough audit of all the places where your old domain appears online.

      For instance, you may have it listed in all your social media bios or in your Google Business Profile:

      Google Business Profile

      Some people may recommend running an audit as a last step, but you’ll want to minimize the time that your old website is listed in these locations. Therefore, it’s best to be prepared and get it done beforehand. It’s important that you make note of all these locations, so you can return to this list later to update your domain.

      Step 3: Migrate Your Site to the New Domain

      After you’ve purchased your shiny new domain name and conducted your audit, you’re ready to get your hands dirty. It’s time to migrate your website to the new domain.

      This process will vary depending on your hosting provider. However, it can be a bit tricky, as it requires moving all of your site’s files and databases.

      If you plan to do it manually, you’ll need to use a Secure File Transfer Protocol (SFTP) client, such as FileZilla:

      FileZilla

      If you’re not confident that you can complete the migration process on your own, you might consider hiring a WordPress developer. You could also check whether your hosting provider offers this service.

      For example, all DreamHost plans come with free migration services, which include WordPress domain transfers. So, if you’ve been meaning to change your hosting provider, now might be a good time to do it.

      Step 4: Set Up Redirects

      Now that you’ve migrated your site, you’ll need to start mapping URLs by setting up permanent (301) redirects. Essentially, a redirect takes users visiting an old URL to your new one. This will be essential for minimizing the negative effects of changing your domain, as broken links can damage your SEO.

      Unless you’re comfortable accessing your site’s core files, the quickest and easiest way to set up your redirects is with a WordPress plugin, such as Redirection:

      Redirection Plugin

      There are many types of redirects, but the 301 redirect is the best option for this scenario. That’s because it’s permanent and will transfer the SEO value of your old pages. Even if you’re using a plugin, you’ll want to do this transition carefully. That way, you can avoid creating redirect errors, which might damage your site’s performance and hurt your SEO.

      Step 5: Update Online SEO Tools & Search Console

      Now, all that’s left to do is wrap up with some digital housekeeping and tell Google, “Hey, I moved my site.” You’ll want to do this immediately after migrating your site and setting up your redirects to avoid any long-term damage to your site’s search engine visibility.

      First, navigate to Google Search Console, to verify your new domain name and submit a Change of Address. This way, Google is made aware of the change and you can continue to monitor your site’s indexing in the search engine rankings:

      Google Search Console

      Additionally, if you have an active Google Analytics account, now is a good time to update it to reflect your new website’s location. You’ll need to repeat this process for any other SEO tools you use. Finally, you can revisit the list you created in your audit (step two) and change all those URL mentions to your new domain name.

      Change Your Domain Name the Right Way

      There are many reasons you may not want to stick with the original domain name you chose for your website. Luckily, you can change your domain with relative ease. However, you’ll need to do it carefully, so you don’t cause your site to drop in the Search Engine Results Pages (SERPs).

      Looking for an easy way to ensure that your site does well in the search rankings? Consider leaving the SEO work to DreamHost’s professionals when you sign up for our Pro Services!

      Search Engine Optimization Made Easy

      We take the guesswork (and actual work) out of growing your website traffic with SEO.

      website tech support



      Source link

      How to Create a Website for Free


      When creating your first website, it can be difficult to find an option that fits your budget. If you’re a blogger or a small business owner, you might want to avoid the monthly fees from custom domain names, hosting plans, and fancy website builders.

      Fortunately, it’s possible to build a website for free (or on a very limited budget). Accessible and user-friendly software such as WordPress.com and Google Sites can help you get a functional site up and running while avoiding unwanted costs.

      In this post, we’ll discuss why you might consider creating a free or low-cost website. Then we’ll show you three different methods you can use. Let’s get started!

      Is the Free Website Option Right for You?

      Building a website can be an important first step in growing your online presence. Whether you want to reach new customers or simply start a blog, you can fully customize a website to suit your specific needs.

      Here’s what any website can do for you:

      • Grow your audience
      • Establish your authority
      • Create a community
      • Provide a place to sell products and services
      • Increase your revenue

      Before you get started, it’s important to know about the typical start-up costs to create a website. You’ll usually need to pay for domain name registration and a web hosting plan to get your site online.

      However, it’s also possible to build a website for free. With a free website, you can:

      • Save costs by avoiding monthly and yearly fees
      • Quickly establish an online presence
      • Avoid the need for coding skills or advanced technical knowledge

      Of course, free website builders do come with some limitations as well. For example, you’ll likely have limited control and customization options when you build a free website. This is fine if you want to create something very small, but you run the risk of your site looking generic.

      free website

      Hosting with free website builder tools does come with some downsides. For example, you may not have much control over page loading speeds. Also, you likely won’t be able to use a unique, professional domain name and instead need to opt for a subdomain (e.g., yourbusiness.freesite.com).

      That said, if you need something straightforward, a free website builder might still be a good option for you.

      Let’s dig in a bit further.

      3 Methods for Creating a Free or Low-Cost Website in 2022

      Method 1: Google Sites (Free)

      Google Sites is a free website builder developed by Google. By simply signing in to Google Workspace, anyone can access this tool. It offers easy-to-use customization features that allow you to build a simple website without any coding experience.

      free Google website

      One of the main benefits of Google Sites is that you can easily integrate other Google services into your website. For example, if you need to add a calendar, you can simply embed your Google Calendar.

      You might want to consider using Google Sites if you’re creating a simple personal blog or a static website. Google Sites could also be the best option for featuring a small, temporary project.

      Unfortunately, Google Sites has limited customization options. Since it is a free service, there are few themes available for personalizing your site’s appearance.

      Step 1: Create a New Site

      To create a free website with Google Sites, navigate to the home page and sign in to your Google account. You’ll need to create a new account if you don’t already have one.

      When you access the Google Sites home page, there will be an option to Start a new site:

      create a free Google website with Google Sites

      You can either begin with a blank site or use one of Google’s pre-designed templates. If you click on Template Gallery, you can view templates for personal, small business, and work use:

      create a free website

      Choose the template that suits your needs. Once you’ve selected one, the program will automatically create a new site. In the top-left corner, you can give your website a name.

      Step 2: Pick a Theme

      Now it’s time to choose your website’s theme. Themes are pre-designed styles you can use to determine your site’s overall look and layout. To see your options, navigate to the right-hand side of the customizer and click on Themes:

      create a free website

      There, you’ll find a variety of free themes to choose from. Simply click on one to apply it to your website. After you do that, you’ll see an option to customize your theme’s colors and font style:

      free website builder

      You can pick from the available color options or use the custom color picker.

      Step 3: Customize Your Content

      Finally, you can change how your website looks by adding a unique title, a banner, and some content. When you click on the area you want to edit, you’ll see various options for changing text, headers, and images:

      create a free website

      You can also add pages, such as an about section, contact page, or blog. To create a new page, navigate to Pages, click on the + icon at the bottom, and give your page a title.

      create a free website

      When you’re ready to add content, go to the side menu and find Insert. There, you can add text boxes, images, or content from your Google Drive. You can choose from the pre-designed layouts to organize a cohesive page:

      create a website with Google Sites

      At the bottom of the page, you’ll see options to embed content from other Google apps:

      For example, clicking on Calendar will connect your Google Calendar to your website. You can follow this process to insert documents, maps, and other unique visuals.

      Method 2: WordPress.com (Free or Low-Cost)

      WordPress.com is one of the most popular site-building platforms. Many people choose to use this platform because it comes with built-in managed hosting. With WordPress.com, you can build a functional website without worrying about any of the technical aspects.

      Here are some of the other benefits to using WordPress.com:

      • Easy to use and maintain
      • Beginner-friendly
      • Free and secure
      • Scalable

      Although WordPress.com started as a blogging platform, you can now use it to create online stores, promote your business, or showcase a personal portfolio. Ultimately, you should consider this option if you’re looking for extra features, security, and support without having to purchase hosting.

      WordPress.com doesn’t cost anything to use, but the free plan only offers up to 3GB of storage space. If you’re planning to feature many photos and videos on your website, you might have to purchase a subscription.

      Additionally, WordPress.com places advertisements on your website. You won’t be able to control this content or where it’s placed. As with Google Sites, you’ll also need to pay extra if you want a custom domain name.

      Step 1: Create an Account

      If you choose WordPress.com to build your site, navigate to the home page and click on Start your website. Then enter your email, username, and password:

      create a free WordPress website

      Next, you’ll be prompted to choose a domain name. You can purchase a domain, which typically costs around $10 per year. However, you can avoid this fee by clicking on start with a free site.

      If you choose that option, “wordpress” will be in your URL. Your site’s domain will look something like this: mysite.wordpress.com.

      Step 2: Pick a Theme

      When you choose a website theme, it’s important to find one that maximizes functionality and aligns with your target audience. Fortunately, WordPress.com has many pre-designed themes to choose from.

      To find a theme, go to your website’s dashboard. Then navigate to Appearance > Themes. Next to the search bar, click on Free to only view no-cost themes:

      free wordpress website

      When you find a theme you like, click on it and select Activate this design. Then hit the Activate button on the following popup.

      WordPress also offers options to customize your theme. To find this tool, go to Appearance > Customize:

      create a free website

      The options you find here will depend on your chosen theme. You may be able to add a background image, alter fonts, change the color scheme, and so on.

      Step 3: Add Content to Your Website

      Finally, you’ll want to add some content to your website. By going to Pages > Add New, you can add new sections. You might want to create an About page, a Contact page, a page for your blog posts, and so on:

      create a web page

      If you’re building a blog, you can navigate to Posts > Add New. There, you can start creating insightful content to build a dedicated audience:

      free WordPress website

      For your first blog post, it’s best to keep your ideal visitors in mind. You can also insert images and write short paragraphs to keep readers engaged. Finally, consider using SEO tools to make it more likely your content will rank highly in search engines.

      When a new page or post is ready, hit Publish. It will then be live for visitors to see!

      Skip the line and get tips right in your inbox

      Click below to sign up for more how-to’s and tutorials just like this one, delivered to your inbox.

      marketing tips

      Method 3: Self-Hosted WordPress (Low Cost)

      There are actually two versions of the WordPress platform: WordPress.com and WordPress.org. As we’ve seen, WordPress.com is a simple hosted website builder. WordPres.org or ‘self-hosted WordPress’ refers to the open-source platform that you can download and use to build any type of website you like.

      WordPress.org offers many advanced features and resources. Especially for business owners who need a functional online store or a site with complex functionality, free website builders such as WordPress.com might not provide enough customization or security.

      To solve this problem, we’d recommend creating a website with WordPress.org. This option won’t be completely free, as you’ll need to purchase a domain and a hosting plan. However, it can still be very cost-effective, and it’s an excellent way to achieve better security and performance on a budget.

      Step 1: Choose a Hosting Plan

      To get started, you’ll need a hosting plan. There are many options out there, some of which are quite expensive. Fortunately, shared hosting plans are very affordable and should give you everything you need to get a starter website up and running.

      Here at DreamHost, we offer shared hosting starting at just $1.99 per month:

      cheap website hosting

      When you choose this plan, you get access to one-click WordPress installation, a free domain, and fast loading speeds. Plus, thanks to automated backups and free privacy protection, you can make sure your website is secure.

      Once you choose a hosting plan, you’ll need to register your site’s domain. In the search bar, enter your domain followed by the TLD (the extension at the end, such as .com or .org):

      register a domain name

      If your chosen domain is available, you can add it to your cart. If it’s already taken, you’ll see a list of alternative options you can pick from.

      Then you can complete the checkout process. When they’re presented, be sure to check the Pre-Install WordPress and WP Website Builder options.

      Step 2: Access WP Website Builder and Choose a Theme

      After you’ve purchased a DreamHost plan, you can access the WP Website Builder. This handy tool comes with over 200 starter sites that you can use as a foundation for your website. Even without coding experience, you can create your own unique-looking website in minutes:

      how to create a website for free

      To access your WordPress site and WP Website Builder, check your email for login information. Then log in to the WP Website Builder setup wizard. There, you can choose from the available WordPress themes.

      Step 3: Customize Your WordPress Website

      After selecting a theme, you can continue to customize your website as needed. If you don’t like your theme’s default look or layout, you can navigate to Appearance > Customize and edit its details.

      One of the many benefits of using WordPress is the ability to install plugins. You can find thousands of free plugins – extensions that add new features and functionality to your site.

      To see what’s available, go to Plugins > Add New. On this page, you can look through the list of popular plugins or search for a specific solution you need:

      free WordPress plugins

      After that, you can also add new pages and content to make your website unique. For example, creating an About page can be a great way to make sure visitors remember and return to your site.

      Get Started On Your New Website Today

      Although creating a website is an important step in building an online presence, it can be expensive. Fortunately, you can avoid high monthly costs by using a free or low-cost platform.

      To review, here are three methods you can use to set up a free or low-cost website:

      1. Google Sites: This simple, easy-to-use website builder can be perfect for creating static personal websites.
      2. WordPress.com: This is one of the most popular website builders and is great for small blogs and portfolios.
      3. Self-Hosted WordPress: If you’re willing to invest in a low-cost hosting plan, you can build your site with the software available from WordPress.org, which offers far more customization and control.

      Sometimes, free website builders don’t offer enough features or security. At DreamHost, our shared hosting plans offer an affordable step up. They come with a free WP Website Builder for fast and cost-effective website creation. Your website can have automatic backups, free privacy protection, and unlimited bandwidth.

      Low-Cost Shared Hosting, Accessible to Everyone

      We make sure your website is fast, secure and always running. Plans start at $1.99/mo.

      shared hosting



      Source link

      How to Set Up a Website Hit Counter With Redis and PHP on Ubuntu 20.04


      The author selected the Apache Software Foundation to receive a donation as part of the Write for DOnations program.

      Introduction

      A hit counter is an application that records and indicates the number of visits your web page has received. The counter starts from 1 and is incremented once every time a web page is visited.

      To keep track of the visits, the hit counter application requires a form of a database. While disk-based database management systems like MySQL can work, an in-memory database is better in terms of speed, performance, scalability, simplicity, and ease of use. This is where the Redis server comes into play. Redis stores data in your computer’s RAM instead of hitting the disk every time you’re performing an input/output operation. This increases the throughput significantly.

      To track your site visits, you require a Redis hash map. This is a data structure that implements a key-value pair. A hash map provides a hash table that maps keys to values. Once a user visits your web page, you create a key based on their public IP address or username (for authenticated users), and then you initialize their total visits to a value of 1. Then, every time the user revisits your web page, you check their total visits from the Redis hash map based on their IP address/username and increment the value.

      In this guide, you’ll set up a website hit counter with Redis and PHP on your Ubuntu 20.04 server. The PHP scripts in this guide use the visitors’ public IP addresses to track their visits.

      Prerequisites

      To follow along with this guide, make sure you have the following:

      Step 1 — Installing PHP Redis Extension

      In this step, you’ll install a Redis extension that allows PHP to talk to the Redis server. You’ll also create a test web page that implements the Redis hash map to track web visits.

      Before installing the Redis extension, refresh your Ubuntu package information index:

      Then, run the following command to install php-redis. The extension provides an API for communicating with the Redis server key-value store:

      • sudo apt install -y php-redis

      Restart Apache to load the new extension:

      • sudo systemctl restart apache2

      You’ve now installed a PHP extension that talks to your Redis server. Next, you’ll create a test.php web page under the root directory of the Apache webserver. This is just a sample file that visitors request when they visit your website with a browser. Under the hood, the test.php page file loads a hit_counter.php script which you’ll later create to track page visits using the Redis server.

      In a real-life scenario, your website might have tens or even hundreds of web pages. For this guide, you’ll set up a single web page for demonstration purposes.

      In your terminal window, use nano to create a new test.php file under the root directory of your web-server /var/www/html/:

      • sudo nano /var/www/html/test.php

      Then, enter the following information into the test.php file:

      /var/www/html/test.php

      <?php
        require_once 'hit_counter.php';
      ?>
      
      <!DOCTYPE html>
      <html>
      
        <head>
          <title>Sample Test Page</title>
        </head>
      
        <body>
          <h1>Sample test page</h1>
          <p>This is a sample test page.</p>
        </body>
      
      </html>
      
      

      Save and close the file when you’re through with editing. In this step, you’ve created a simple HTML web page that loads a hit_counter.php file when visited. Next, you’ll code the hit_counter.php file to track the test page visits.

      Step 2 — Creating a Redis Hit Counter Script

      When working in a production environment, it’s very conventional to separate re-usable PHP files. This allows you to implement the logic in these files on different parts of the project just by including their paths instead of copy-pasting the code. This makes maintenance easier since you only need to edit a single file in case you need to change the logic. This saves you a lot of time.

      You’re going to apply the same strategy in this guide. You’ll create a single hit_counter.php file that you can include on any web page that requires visitors’ tracking.

      In this file, you’ll use the php-redis library to connect to the Redis server from PHP. Then, you’ll create a Redis hash map to store the number of visits a visitor has made to your website. You’ll use the visitors’ unique IP addresses as Redis keys to distinguish each visitor’s hit counts in the Redis server.

      In your terminal window, open a new hit_counter.php file using nano for editing purposes:

      • sudo nano /var/www/html/hit_counter.php

      With the hit_counter.php file now created, open a new PHP tag <?php. Then, inside a try { block enter the following code to connect to your local Redis server on port 6379. Replace EXAMPLE_PASSWORD with the authentication password for the Redis server:

      /var/www/html/hit_counter.php

      
      <?php
      
          try {
      
              $redis = new Redis();
              $redis->connect('127.0.0.1', 6379);
              $redis->auth('EXAMPLE_PASSWORD');
      

      Next, give the Redis hash map($siteVisitsMap) a name of your choice. This guide uses siteStats for demonstration purposes:

      /var/www/html/hit_counter.php

      
              $siteVisitsMap = 'siteStats';
      
      

      After defining the Redis hash map, you’ll now initialize an empty Redis key ($visitorHashKey). Then, you’ll populate it with the visitors’ IP addresses. You’ll use the value of the $visitorHashKey variable to uniquely identify each visitor requesting your web page:

      /var/www/html/hit_counter.php

      
      
              $visitorHashKey = '';           
      
              if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
      
                  $visitorHashKey = $_SERVER['HTTP_CLIENT_IP'];
      
              } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
      
                  $visitorHashKey = $_SERVER['HTTP_X_FORWARDED_FOR'];
      
              } else {
      
                  $visitorHashKey = $_SERVER['REMOTE_ADDR'];
              }
      
      

      In this code, you’re using the PHP if statement to determine the visitor’s IP address by checking whether the $_SERVER['HTTP_CLIENT_IP'], $_SERVER['HTTP_X_FORWARDED_FOR'], or $_SERVER['REMOTE_ADDR'] variables are populated.

      Following this, initialize a $totalVisits variable to store the total visits for each IP address and assign it a value of 0. Then, use the PHP if (...) {...} else {...} and $redis->hExists($siteVisitsMap, $visitorHashKey) statements to check if the IP address has any entries in the Redis server.

      You’ll use the statement if ($redis->hExists($siteVisitsMap, $visitorHashKey)) {...} to check whether a $visitorHashKey exists in a map named $siteVisitsMap.

      In case the map and the key with the named IP address exist in the Redis server, retrieve it with the statement $visitorData = $redis->hMget($siteVisitsMap, array($visitorHashKey)); and use $totalVisits = $visitorData[$visitorHashKey] + 1; to increment the $totalVisits variable. You’re using the $redis->hMget statement to get hit count data associated with an IP address. The hMget function accepts the name of your map ($siteVisitsMap) and an array of the keys that you want to retrieve from the Redis server. In this case, you only have one key ($visitorHashKey), but you must convert it to an array using the statement array($visitorHashKey).

      In case your script encounters the IP address for the first time, set the $totalVisits variable to 1. Finally, use $redis->hSet($siteVisitsMap, $visitorHashKey, $totalVisits); to set the value of the $visitorHashKey according to the results of the previous if (...) {...} else {...} statement. The $redis->hSet($siteVisitsMap, $visitorHashKey, $totalVisits) statement creates a $siteVisitsMap hash map in the Redis server with a key named $visitorHashKey with a value of $totalVisits.

      Then, welcome the visitor by echoing the total visits and close the } catch (...) {...} block:

      /var/www/html/hit_counter.php

      
              $totalVisits = 0;
      
              if ($redis->hExists($siteVisitsMap, $visitorHashKey)) {
      
                  $visitorData = $redis->hMget($siteVisitsMap, array($visitorHashKey));
                  $totalVisits = $visitorData[$visitorHashKey] + 1;
      
              } else {
      
                  $totalVisits = 1;
      
              }
      
              $redis->hSet($siteVisitsMap, $visitorHashKey, $totalVisits);
      
              echo "Welcome, you've visited this page " .  $totalVisits . " timesn";
      
          } catch (Exception $e) {
              echo $e->getMessage();
          }
      
      

      Once completed, your /var/www/html/hit_counter.php file should be similar to the following code:

      /var/www/html/hit_counter.php

      
      <?php
      
          try {
      
              $redis = new Redis();
              $redis->connect('127.0.0.1', 6379);
              $redis->auth('EXAMPLE_PASSWORD');
      
              $siteVisitsMap  = 'siteStats';
              $visitorHashKey = '';           
      
              if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
      
                 $visitorHashKey = $_SERVER['HTTP_CLIENT_IP'];
      
              } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
      
                 $visitorHashKey = $_SERVER['HTTP_X_FORWARDED_FOR'];
      
              } else {
      
                 $visitorHashKey = $_SERVER['REMOTE_ADDR'];
              }
      
              $totalVisits = 0;
      
              if ($redis->hExists($siteVisitsMap, $visitorHashKey)) {
      
                  $visitorData = $redis->hMget($siteVisitsMap,  array($visitorHashKey));
                  $totalVisits = $visitorData[$visitorHashKey] + 1;
      
              } else {
      
                  $totalVisits = 1;
      
              }
      
              $redis->hSet($siteVisitsMap, $visitorHashKey, $totalVisits);
      
              echo "Welcome, you've visited this page " .  $totalVisits . " timesn";
      
          } catch (Exception $e) {
              echo $e->getMessage();
          }
      

      Save and close the file when you’re through with editing. You’ve now coded a hit_counter.php script. Next, you’ll create another PHP script that generates a report from the data gathered in the Redis hash map.

      Step 3 — Creating a Site Stats Report Script

      Once you’ve collected data in a Redis hash map, it might not make any sense if you’re not able to retrieve and represent the information in a report. In this step, you’ll create a log report to show the different site visitors and the total visits they’ve made on the test web page.

      To create the log report script, run nano on your terminal window and create a new /var/www/html/log_report.php file:

      • sudo nano /var/www/html/log_report.php

      Then, enter the information below into the file. Replace EXAMPLE_PASSWORD with the correct password for the Redis server:

      /var/www/html/log.php

      
      <!DOCTYPE html>
      <html>
      
        <head>
          <title>Site Visits Report</title>
        </head>
      
        <body>
      
            <h1>Site Visits Report</h1>
      
            <table border="1">
              <tr>
                <th>No.</th>
                <th>Visitor</th>
                <th>Total Visits</th>
              </tr>
      
              <?php
      
                  try {
      
                      $redis = new Redis();
                      $redis->connect('127.0.0.1', 6379);
                      $redis->auth('EXAMPLE_PASSWORD');
      
                      $siteVisitsMap = 'siteStats';                          
      
                      $siteStats = $redis->HGETALL($siteVisitsMap);
      
                      $i = 1; 
      
                      foreach ($siteStats as $visitor => $totalVisits) {
      
                          echo "<tr>";
                            echo "<td align = 'left'>"   . $i . "."     . "</td>";
                            echo "<td align = 'left'>"   . $visitor     . "</td>";
                            echo "<td align = 'right'>"  . $totalVisits . "</td>";
                          echo "</tr>";
      
                          $i++;
                      }
      
                  } catch (Exception $e) {
                      echo $e->getMessage();
                  }
      
              ?>
      
            </table>
        </body>
      
      </html>
      

      Save and close the file when you’re through with editing. In the above script, you’re connecting to the Redis server and you’re using the statement $redis->HGETALL($siteVisitsMap); to retrieve your web page visits’ hash map. Then, you’re using the PHP foreach ($siteStats as $visitor => $totalVisits) { statement to loop and display the visitors’ IP addresses and the number of visits they’ve made to your site. You’re using the Redis HGETALL command to retrieve all fields (IP addresses) and values (total visits per each IP address) from the siteVisitsMap map.

      You now have a test page, a hit counter script, and a report page to check your site stats. Next, you’ll test the functionalities of your hit counter and see if everything works.

      Step 4 — Testing the Redis Hit Counter

      In this step, you’ll test the whole logic for your hit counter. Navigate to the following URL on your web browser. Replace your-server-IP with your server’s public IP address or domain name.

      http://your-server-IP/test.php
      

      Refresh the page several times using different devices to generate enough stats. After each visit, you should receive the following output.

      https://www.xpresservers.com/wp-content/webpc-passthru.php?src=https://xpresservers.com/wp-content/uploads/2021/12/How-to-Set-Up-a-Website-Hit-Counter-With-Redis.png&nocache=1

      Next, visit the following URL to get your site visits report displayed in an HTML table

      http://your-server-IP/log_report.php
      
      

      You should now see a report similar to the following output.

      https://www.xpresservers.com/wp-content/webpc-passthru.php?src=https://xpresservers.com/wp-content/uploads/2021/12/1640824415_889_How-to-Set-Up-a-Website-Hit-Counter-With-Redis.png&nocache=1

      Your hit counter is now working as expected.

      Conclusion

      In this guide, you’ve set up a website hit counter with Redis and PHP on your Ubuntu 20.04 server.

      As you can see from the sample source code in this guide, Redis provides cleaner methods for creating and updating hash maps.

      As mentioned at the beginning of this guide, using a relational database management system may still work but you’ll write tons of code to insert and update data in underlying tables. In addition, disk-based databases may experience scalability issues when your site grows.

      For more information on using Redis in-memory database, follow the guides below:



      Source link