One place for hosting & domains

      Website

      How to Run an Online Giveaway on Your WordPress Website


      Thinking of innovative ways to engage with your website visitors and social media followers can be a challenge. Creating fun and appealing activities might be on your list of marketing strategies to explore, but it’s hard to know where to start.

      Fortunately, online giveaways are a popular and easy way to engage loyal customers, gain new followers, and even encourage user-generated content focused on your brand. What’s more, contests can be a productive way to find new leads.

      In this article, we’ll discuss the benefits of using giveaways to promote your business. We’ll also take a look at 10 giveaway tools you can use to create a successful contest.

      So come on down — the prize is right!

      Why Your Business Can Benefit From Giving Products Away

      Online giveaways and contests can be highly effective ways for your business to attract and keep new customers. At a basic level, they can help to build trust and loyalty for your products. However, the benefits of running contests and giveaways go even further than that.

      When it comes to spreading the word about your business, a giveaway can be highly valuable. For example, 95% of people who participate in a contest or giveaway share it with friends online afterward (everyone wants to win a prize). That’s a pretty wide reach for something you can often set up for free. We’ll cover some of the ways you can do that later in this article.

      You can also build your email list by using contests to collect user information. In fact, some giveaway apps also include a social sign-in functionality, which has been shown to increase the success rate of online marketing campaigns. This feature gives users the option to sign in to your website or contest using a social media account they already have, saving them from having to create an entirely new account.

      Win Big with DreamPress

      Our automatic updates and strong security defenses take server management off your hands so you can focus on your giveaway, not downtime.

      How to Develop an Online Giveaway Strategy That Works

      One of the first steps in carrying out a successful online giveaway is to set explicit goals from the start. Planning out all the details of the giveaway is vital, as you don’t want to have a game go astray or forget a critical component of the rules.

      More specifically, setting measurable goals for your contest will make it more valuable when you crunch the numbers later and assess whether the Return On Investment (ROI) was worth it. You’ll want to identify whether your goal is to convert leads, gain new leads, promote a product or service, or something else entirely. Then you’ll need to consider exactly how that goal will be measured, so your results will be crystal clear.

      Contests and giveaways are also excellent at encouraging user-generated content (UGC). This is a way for brands to invite their followers and customers to contribute to the company’s story online. Contests are one way to do this. For example, check out LEGO’s Moments in Space contest.

      Lego’s “Moments in Space” contest.

      Since 64% of marketers agree that building community is essential to their marketing strategies, combining UGC with giveaways and contests is a smart move.

      It’s also vital to clarify the type of promotion you’d like to run as you begin to develop your strategy.

      • Sweepstakes are prize giveaways where a winner is chosen at random by luck of the draw.
      • Contests choose a winner based on merit, such as in the above LEGO contest.
      • Lotteries are prize drawings where people have to pay to play — you’ll definitely want to consult with legal counsel before setting one of these up.

      Whatever type of promotion you decide to run, make sure that you stay on the right side of giveaway rules in your state (or country) since there could be legal ramifications.

      There are lots of options for running giveaways on your WordPress website. However, it’s worth noting that, while some of the applications on our list have well-maintained WordPress plugins, others do not. Let’s go over everything you need to know about 10 popular giveaway solutions that you can start using on your website right now.

      1. RafflePress

      The RafflePress plugin.

      RafflePress is a free plugin for WordPress with premium upgrade options. It provides a comprehensive package for creating and managing giveaways on your website. This solution comes with a drag-and-drop giveaway builder, fraud protection, viral sharing functionality, and templates. Additionally, it offers tracking and retargeting features, which can help you make an even more significant impact with the work you put into running giveaways.

      Price: RafflePress has a free plugin for WordPress. Alternatively, you can upgrade to a premium plan starting at $39.20 per year for a one-site license or $359.20 for an unlimited, lifetime license.

      2. Woorise

      The Woorise website.

      Woorise is an application that enables you to create a variety of interactive contest elements for your website with a drag-and-drop editor. There is a WordPress plugin for Woorise, but it has not yet been thoroughly tested and vetted, so we recommend caution. In the meantime, you can create what you need through the platform’s website and embed it wherever you need to on your site.

      Price: Woorise has a free plan that covers 500 entries, or you can upgrade to one of its annual tiers that all come in just under $100 per month.

      3. Easypromos

      The Easypromos website.

      Easypromos is a more extensive software system with many options and lots of giveaway templates for a quick start-up process. You can create campaigns using 30 different applications designed for specific social media channels, as well as games, quizzes, and coupons. All of these can be embedded on your WordPress website using a custom HTML block or widget.

      Price: Easypromos’ pricing is a bit more complicated than some of the other options on our list. You can price a single promotion, purchase the Giveaway app starting at $29 per month, or get all of the company’s applications starting at $159 per month.

      4. Heyo

      The Heyo website.

      Heyo offers 11 different products and services that are all geared towards building engagement for your brand. You can use them to create various types of photo contests, giveaways, sweepstakes, quizzes, and contests (and even multiformat contests). To use this application with WordPress, you’ll need to create your giveaway within Heyo and use embed codes to add it to your website.

      Price: You can choose from Basic, Standard, or Premium plans starting at $25 per month for a year-long contract or contact the company for custom account pricing. There’s also a seven-day free trial offer.

      Be Awesome on the Internet

      Join our monthly newsletter for tips and tricks to build your dream website!

      5. Rafflecopter

      Rafflecopter giveaway website.

      Rafflecopter is a popular and well-known contest application. It has a very beginner-friendly interface that makes it easy to get a contest up and running quickly. Once you create a contest, you can share it with your social media channels, link it to your website, or embed it on a web page. Rafflecopter’s reputation is one of success, innovation, and quality support.

      Price:  You can start with a free plan or upgrade to the Basic plan for $13 per month. There are also Grow ($43) and Premium ($84) plans that can be upgraded on a month-to-month basis for greater flexibility.

      6. Gleam

      The Gleam website.

      Gleam offers four different applications that cover contests, galleries, rewards, and “capturing.” This means you can create redeemable rewards for your site’s users in return for actions such as sharing your content on social media. You can also use the capture feature to attract more email subscribers. All in all, Gleam is a very visually-engaging option for embedding contests on your WordPress website.

      Price: You can get all four applications in an easy-to-use dashboard for $97 per month or purchase just the apps you need for lower monthly payments. For example, the competition app starts at $10 per month.

      7. ShortStack

      The ShortStack website.

      This platform offers a very comprehensive approach to marketing your online products or services. ShortStack collects a seemingly endless number of features and options in one place. Beyond contests and giveaways, ShortStack also offers data management and team collaboration solutions.

      Price: ShortStack provides a free plan with limited options. You’ll have to look at its Business plan ($99 per month) or higher to take advantage of the “Embed to WordPress” and popup features.

      8. Wishpond

      The WishPond website.

      Wishpond offers an integration tool for WordPress and has many marketing solutions to choose from. Contests and giveaways are just the tip of the iceberg with Wishpond. If you’re looking for a giveaway platform that also includes a healthy dose of marketing and engagement tools, this might be your best bet.

      Price: Do-it-yourself plans start at $49 per month, but you will have to contact the company for managed account pricing.

      9. Woobox

      The Woobox website.

      You can run a wide variety of campaigns with Woobox. It includes options for bracket contests, instant winners, and a “winner picker” feature. One of the benefits of Woobox is that you can choose from many pre-built templates and then customize them to match your needs.

      Price: You can start with the limited free plan or upgrade to a Standard plan for $32 per month for unlimited entries.

      10. KingSumo

      The KingSumo website.

      If you’re looking for a truly integrated approach to giveaways, KingSumo is a great option. This application is focused on viral giveaways. You can build your campaigns with their dedicated WordPress giveaway plugin right in your website’s admin panel.

      Price: A lifetime, single-site license is $198 and includes free updates and customer support. A developer’s license costs $594 for unlimited sites.

      How to Market and Improve Your Contest

      Promoting your website online can be challenging, partly due to an overwhelming slate of options. The good news is that giveaways can be fun and engaging, as well as cost-effective. Of course, once you create your giveaway, you’ll need to promote it as well. Here are some low-cost ways of getting your giveaway content out in front of potential participants.

      If you want some insights on how to best use your social networks, check out our social media for small business guide.

      Another important aspect of running a contest (especially if you also want to collect valuable marketing data on your target audience) is to include a way for entrants to send you feedback on their experiences.

      This could be a simple rating system or a follow-up email with an invitation to complete a survey. Either way, it can be very helpful in determining how to make your next contest experience even better. Plus, it gives you a chance to revamp any elements that didn’t work out the first time.

      Eye on the Prize

      Aside from being good fun, contests and giveaways have an excellent track record of driving conversions, improving engagement, and boosting brand awareness. Understanding the benefits of running a quality contest and driving entries can help you hone in on all the right elements to include.

      There are plenty of reputable contest applications and plugins to help. Whether you choose Rafflecopter, Woorise, ShortStack, Rafflepress, or one of the others we’ve reviewed, you’ll be well placed to run a fully-featured giveaway.

      If you need some more plugin recommendations for your website, you’ve come to the right place. We’ve put together a ton of guides to help you choose the right add-ons for your WordPress site.

      Of course, you’ll also need to make sure your web host is up to the task. Here at DreamHost, we have managed WordPress hosting plans that can help you ensure a safe, secure, and seamless contest experience for your customers!



      Source link

      Want to Build a Website in 2020? Here’s Your Game Plan


      Feeling committed to making this year better than the last? You’ve probably got your personal goals all set for the new year: read more books, call your mom, eat less pizza, walk off that holiday pie.

      How’s this for a New Year’s Resolution: Build a successful website from the ground up. Sounds like a lofty goal, but trust us, kid — you’ve got the makings of a champion.

      via GIPHY

      Building an online presence is like running a marathon. Those exhausting 26.2 miles require long-time endurance built over months of training. Marathoners train one step at a time and complete one mile at a time.

      This guide is your training plan. 

      As your trusty web host and coach, we’re here to keep you on track as you build, grow, secure, and promote your new site. We’ve broken this website workout plan into goals and tasks to complete each quarter throughout 2020, but feel free to work at your own pace. You do the sweating, and we’ll be right beside you with step-by-step instructions, water cups, and cheese-tastic motivational signs.

      1. Build Your Website 
      2. Grow Your Website
      3. Secure Your Website
      4. Promote Your Website

      Sound good? Then tie up your Nikes, pull on your gym shorts, and let’s get to work.

      First Quarter: Build Your Website

      Step 1: Decide on Your Mission

      Ready to race right off the starting block into building your website? We love the enthusiasm. But before even reaching the starting line, you need to get in some warm-ups and conditioning to establish a solid foundation. Every good website begins with a thoughtful plan. Open a fresh new digital doc (or grab a pen and paper if you’d prefer to go old school) and complete the following exercises.

      Find Your Purpose

      Why do you want a website in the first place? What do you hope it will accomplish? Ask yourself, “What is the purpose of this website?”

      The possibilities are endless — but you need to spell out what you want and who your target audience is. Write down what you decide; you’ll use this purpose to guide everything else you do this year.

      Set Goals

      Time to dive deeper into the reflecting and set some specific goals for your website. Grab your pen (or ready your typing fingers) and, below your website’s purpose, jot down a few goals. There are lots of options.

      • Site revenue
      • Site Traffic
      • More customers in your physical store
      • More followers on social media platforms
      • Number of business contacts or leads from your site

      These goals should accomplish your website’s purpose and drive the rest of your plans.

      Don’t lose sight of your finish line — and don’t be afraid to adjust your goals over the coming months.

      Outline Your Content

      You probably shouldn’t bake a cake without a recipe. Likewise, you can’t build your website until you know what components you need to make it a success. So go ahead and outline your content to make sure you hit your goals. Consider these components:

      • Start with your website’s menu. What should its offerings include? And in what order? Rank what’s most important to you — and your goals — at the top.
      • Do you want to include a blog? This will be helpful for search engine optimization (SEO) — more on that in a minute — encourage engagement and community, build your reputation,  and establish you as an expert. If the blog is the cornerstone of your site, take some time to outline (or, for overachievers, write) your first few posts and plan some topics you might write about over the next year.
      • The “About Me” page is your place to tell your story and describe your business. Don’t skip out on this chance to connect with your customers.
      • Do you need a spot to describe the products or services you’re selling, either online or in your physical store? If your objective is to drum up business directly from the web page, this is essential. Think about categories and subcategories of products, and consider how you might describe or sell them to your website visitors.
      • What is included on the homepage? Your contact information? Maybe, although that could easily be its own page. A memorable photo? Definitely. Another homepage must-have? A call to action (CTA). Your CTA should invite visitors to do something: check out your offerings, sign up for your newsletter, or delve into your blog.

      Step 2: Choose a Domain and Platform

      Ready. Get set. We are inching closer to launching your website, but before we can get going, it first needs a name and a place to live.

      Pick a Domain Name

      Basically, a domain is what you type into the bar at the top of your browser to point to a specific website. For example, to find us a DreamHost, you type in dreamhost.com. A domain consists of two parts:

      1. The top-level domain (TLD) — In dreamhost.com, the “.com” part is our TLD. The more common TLDs include .com, .net, .org, .info. You can even choose something jazzier, like one of the new TLDs: .party, .site, .pizza, .limo, .store, and more. At least for now, though, .com is still the most common TLD.
      2. The second-level domain (SLD) — In our domain name, that’s “dreamhost.” This is the keyword that will serve as the address for your website. Make sure it is specific, descriptive, and memorable so that customers can easily find and remember it.

      Jot down a dream domain and see if it is available for purchase. If you can’t find (or afford) your first-choice domain name, we’ll help you find other great options.

      Pick a Hosting Plan

      If your domain name is your website’s address, hosting is the physical space (spoiler: a server) where your website lives. The hosting plan you choose for your website will impact many things — like how fast your site loads and what kind of maintenance you have to do.

      DreamHost offers several great options to cover a variety of web hosting needs (not that we are biased about this at all, ahem).

      For beginners, we recommend shared hosting. It is affordable, fast, and meets the needs of any basic website (and includes a free domain registration!). You can always upgrade as your website grows.

      Shared Hosting That Powers Your Purpose

      We make sure your website is fast, secure and always up so your visitors trust you. Plans start at $2.59/mo.

      Choose a Platform

      To build your website, you’ll need to pick a platform — and there’s no content management system (CMS) better, in our opinion, than WordPress. And 75 million websites agree with us. Like any powerful tool, there is a learning curve to WordPress, but the open-source software is free to use and pretty beginner-friendly.

      Step 3: Design and Launch

      OK — with a set of goals, a content outline, a domain, web hosting, and a platform picked for your new website, it is finally time to get building!

      Build Your WordPress Website

      Head over to DreamHost’s WordPress hosting page, pick the plan that’s right for you, install WordPress, configure your settings, and start building your website. Pull out the list of goals and content outline you made in step one, and use it to guide you in choosing a theme that matches your brand.

      Learn About Web Design Trends and Best Practices

      No, you don’t need to become an expert overnight. And never fear: those WordPress themes we just mentioned are beautiful and will save you from major design blunders. But here are a few basic pointers to keep in mind as you get started in designing your site.

        1. Keep things quick and straightforward — From homepage copy to navigation options, think short and sweet.
        2. Don’t fear the blank space — Don’t feel the need to fill every nook and cranny; elegant emptiness can go a long way.
        3. Keep your menu front and center — Keep it easy to find or risk losing visitors.
        4. Mind your typographyWhat you say matters as much as how you say it — and what it looks like.
        5. Pick a color scheme that matches your brand — Color communicates, so pick ones that fit the ethos of your website.
        6. Make it accessible — Expand your audience by making sure your website is usable by everyone, including individuals with disabilities.
        7. Use templates — When you sign up for a DreamHost plan, you’ll have the option to include WP Website Builder with your account. This tool makes it easy to use customizable and professional templates to design a beautiful, fully functional WordPress website. To prove just how versatile this tool is, we put together a tutorial series that demonstrates how you can use WP Website Builder templates to start fitness blogs, food blogs, photography blogs, real estate websites, and restaurant sites (to name a few)!

      If you lack the skills (or time to learn the skills) to design a website — and have some wiggle room in your budget — consider hiring a professional designer to help you customize your site’s look.

      Launch!

      Go ahead. Send your website out into the world. Take a quick victory lap — you’ve earned it! But don’t lose your momentum; the work has only started.

      Second Quarter: Grow Your Website

      So now you have a website. Yay!

      Time to beef it up with some strength training. That’s right. Once your site is up and running, turn your attention to attracting more visitors and bringing in some income.

      Step 4: Monetize Your Site

      Ready to bring in the big bucks with a blog or online store? Let’s get you set up.

      • Review your offerings — Take a look at the products and services you are selling. Is there anything else you can add, especially to entice back past customers? Have you thought about adding an online course or premium for-pay content to your blog?
      • Add some ads — Include a bit of subtle, tasteful advertising on your WordPress blog to bring in some additional revenue.

      • Affiliate marketing — Incorporating affiliate links on your blog or website is another way to add to your revenue stream. Basically, you’ll promote another brand’s product and provide links to their site. If your readers click and make a purchase, you’ll get a cut of the sale in thanks for your referral.
      • Investigate e-commerce solutions — How are you planning to sell and accept payment on your website? You’ll need to get that squared away before promoting your online store. If you’re using WordPress, we recommend Woocommerce (so much so, that we’ve even got hosting just for Woocommerce users). Study up on the world of e-commerce and pick an online payment gateway (watch out for sneaky transaction fees).

      Step 5: Adopt SEO Best Practices

      Once your site is built and prepped to be monetized, you are ready to reel in the traffic with SEO.

      SEO is a group of strategies website owners can (and should!) use to appear closer to the top of the results on search engines.

      Think about it: when you search for something on Google, you probably only scan the first few entries before clicking — and so will your clients. Since Google bases its results ranking on a variety of factors, it’s essential to do the following:

      • Brainstorm keywords relevant to your site — What search phrases do you think (or hope) would most likely lead readers to your website? Use Google’s Keyword Planner to research and discover new keywords.
      • Optimize your blog posts — Plan content around these keywords and make sure to use them in your posts and headings — but be careful and creative with your placement to avoid creating content that sounds forced. If you need help getting started, check out these SEO tools.
      • Keep it fresh — Regular updates and new content will give you a search-ranking boost. But don’t be afraid to freshen up and repurpose old content.
      • Create a sitemap — Sitemaps, which are basically a hierarchical list of all the pages and content on your site, help Google’s search engine crawlers see and connect the pages on your site, making it easier to present relevant information in search results.

      Step 6: Take Care of the Details

      Now that your site has been up and running for a while, it’s time for some spring cleaning. Let’s make sure your website is up to par and easy to access for all your potential customers.

      Clean and Polish

      Start with a few routine upkeep tasks, and set reminders to do them again in another six months:

      • Check for broken links.
      • Review and edit website copy and high-traffic blog posts.
      • Update contact information and your “About Me” section.
      • Test functionality of forms and checkout.
      • Think about your user experience. How can you make it better?
      • Review your hosting plan — are you ready for an upgrade?

      Go Mobile

      Take a look at how your site looks on the small screen. If your website isn’t optimized for mobile — that is, if it doesn’t look as good and load as fast on mobile devices as it does on a computer — you’re missing out. Responsive design matters in 2020.

      Many potential customers use phones or tablets in place of a home computer, and some shop on the go. Plus, your Google search rankings could hurt if your website isn’t mobile-friendly. Pull your website up on your smartphone, and make any necessary changes.

      Review Your Traffic

      If you haven’t already, install Google Analytics onto your WordPress website. Google Analytics is a plugin that tracks and analyzes key data about your website, including:

      • Page views — At a glance, this stat will reveal your most popular pages and posts in the past day, month, and year.
      • Unique visitors — Using IP addresses, Google Analytics will track how many unique visitors your site attracts.
      • Bounce rate — Sometimes visitors will click away from your site after viewing only one page; this stat will let you know how often that dreaded “bounce” happens.
      • Session duration — When someone visits your site, how long do they stick around? Check this number for the answer.
      • Traffic source — You might suddenly see an increase in traffic to a particular page, and Google Analytics will help you pinpoint what link is sending the visitors.

      Studying these statistics will help you find changes to make to draw more visitors and encourage them to stay longer (and hopefully make a purchase).

      Third Quarter: Secure Your Website

      Time to work on endurance: You want your website to stick around for the long haul. Now it’s time to beef up your security practices and protect your data.

      Step 7: Tighten Website Security

      When it comes to security, you can rest easy at night: you’re already on the right track to keeping your information and customer’s data safe with WordPress and DreamHost. But there are a few additional steps you can take to tighten up security.

      • Switch to HTTPS — The “S” in HTTPS stands for “secure,” and it is (surprise) the more secure version of HTTP, encrypting your data as it is transferred from your website to a user’s browser. Add that all-important “S” by getting an SSL/TLS certificate (offered for free with all DreamHost hosting plans).
      • Enable a firewall — You probably have a firewall on your computer, protecting you from unwanted attacks. And, if you’re one of our customers, lucky you: DreamHost includes a built-in Web Application Firewall (WAF) to offer your website similar protection.
      • Use two-factor authentication — This will require you to sign in to your site with a code that’s first sent to your mobile phone. While it can be a bit of a hassle on your end, this step goes a long way in keeping your site secure. Use a WordPress plugin like Two-Factor Authentication.
      • Add an SSL security certificate — At DreamHost, we want you and your website’s users to feel confident about their data and financial transactions. We also want you to be able to focus on building your website’s following — that’s why we offer SSL/TLS certificates free with all of our hosting plans!
      • Backup your site — Hackers gonna hack. Even with all your efforts to secure your site, security breaches and other disasters are still a possibility. So make sure to regularly backup your website. That way, if the unthinkable happens, you won’t lose all of your digital property.
      • Scan for malware — Hackers can really mess things up for your website by installing malware, which can mess with the code and steal secure data. Scan your site regularly to make sure it’s clean. DreamHost customers can sign up for DreamShield, an add-on that will automatically scan your site for malware.
      • Pick a strong password — Don’t make it easy for just anyone to walk into your digital front door; choose a password that is long, uncommon, and used only for your website.

      Step 8: Speed Things Up

      Nothing is more of a drag than a sluggish website. Keep your website up to speed by:

      • Installing a caching plugin for faster load times — The “cache” is where your computer stores recently used information, such as the files of a recently visited website. A caching WordPress plugin pulls data from the local cache instead of reloading it fully every time, thus speeding things up.
      • Optimizing your images — High-res photos can take an extra-long hot second to load, but there’s no need to sacrifice quality.
      • Testing your speed — Even if it seems like your page is loading normally, get in the habit of regularly testing your speed. Simply type your URL into Google’s PageSpeed insights for a quick analysis and tips to get a faster score.

      Step 9: Prepare for Trolls

      By the time you’ve reached this step, you’ve probably got fans. But as your site builds a community, it will also attract some of the slimier creatures lurking in the anonymity of the web: spammers, trolls, and cruel commentators. Keep these thoughts in mind as you deal with the underbelly of the web:

      • Don’t feed the trolls — This is rule No. 1 when it comes to trolls. Don’t engage; it will just feed the fire.
      • Understand the difference between trolling and disagreement — Not everyone who disagrees with you is a troll; usually, they are legitimate readers with a different viewpoint. Feel free to defend yourself and your arguments, and be open to changing your mind — and reminding aggressive commenters to play nice.
      • Establish a commenting policy — Spell out for your readers how you expect them to behave, what the consequences are for violations, and make clear that trolls are not invited to the party.
      • Block or delete — If a trolling post gets too out of hand, don’t be afraid to step in and shut it down.

      Fourth Quarter: Promote Your Website

      Congratulations! You’re officially three-quarters of the way through this marathon [splashes water on face]. Don’t lose that momentum; continue strong and steady to the finish line. Think of all the orange slices awaiting you. To get there, your next task is promotion.

      Step 10: Advertise

      You’ve got a great thing going, and it’s time to tell the world. Advertising, even for the beginner website owner, is a no-brainer that can be simple, effective, and affordable. Try your hand at two basic types of targeted advertising:

      Pay-Per-Click Advertising

      A good SEO strategy will organically move you to the top of the search results. With Pay-Per-Click (PPC) ads, you’ll take matters more into your own hands by paying to land atop the search engine result pages (SERPs). The best part? You only have to pay for premium placement if someone clicks on your link. You choose the keywords you want to bring up your ad, and you can set and limit your own budget.

      Social Media Advertising

      Facebook is a well-oiled, data-collecting machine, and you can use its power to target advertising directly to your ideal audience. You can create a Facebook ad that reaches users based on specific info such as age, gender, interests, etc. As with Google Adwords, you’ll set a budget and pay for clicks. Get on Instagram and leverage your feed and stories for some great free advertising for your brand. Follow this guide to narrow down which social media platform you should use for your business.

      Step 11: Market with Email

      Email is one of the best tools your e-commerce site has for finding new customers, bringing back previous ones, and maintaining relationships.

      Learn the Basics

      Study up on email marketing, a tried-and-true marketing method that involves collecting email addresses as a way to share content and build relationships with current and potential customers.

      Collect Email Addresses

      You can’t send any mail if you don’t know where it’s going. But don’t be spammy and shady about it; create opt-in forms directly on your site inviting visitors to subscribe. Try offering something in exchange for an email address, such as a discount off a first purchase or access to a free ebook.

      Create an Email Newsletter

      Email newsletters remain one of the best ways to connect with your customers, so create one and make it the center of your email marketing strategy. Use it as a way to showcase your voice and your brand, share news and upcoming events for your business, and introduce new products (but don’t be too pushy). Send it out regularly, loaded with fresh content, and then solicit feedback.

      Be Awesome on the Internet

      Join our monthly newsletter for tips and tricks to build your dream website!

      Bring Your Customers Back

      Beyond a newsletter, what other types of emails will engage your customers? Always send purchase receipts and make sure to welcome new subscribers. Consider reaching out to past customers to announce sales, share discounts, and invite them back to the fold.

      Step 12: Get Creative

      Now that you’ve covered your bases with advertising and email marketing, dig deeper and get a little creative in extending your website’s reach. Try out these promotion ideas:

      You’ve made it to the finish line! You’ve worked hard, and your website is certainly one to be proud of. Now, hit the showers, champ.

      And if you haven’t launched your site yet, we’re here for you. Start off on the right foot with DreamHost’s shared hosting plan. It’s the most affordable way to make all your website dreams come true — seriously, plans start at just $2.59/month — without sacrificing quality and performance. Create your website today!



      Source link

      Como Criar e Exibir Imagens WebP para Acelerar Seu Website


      O autor selecionou a Apache Software Foundationpara receber uma doação como parte do programa Write for DOnations.

      Introdução

      WebP é um formato aberto de imagem desenvolvido pelo Google em 2010, baseado no formato de vídeo VP8. Desde então, o número de sites e aplicativos móveis que usam o formato WebP cresceu rapidamente. Tanto o Google Chrome como o Opera suportam o formato WebP de forma nativa e, uma vez que esses navegadores representam cerca de 74% do tráfego da Web, os usuários podem acessar sites mais rapidamente se esses sites usarem imagens WebP. Também existem planos para implementar o WebP no Firefox.

      O formato WebP suporta tanto a compressão de imagens com perda, quanto sem perda de dados, incluindo animação. Sua princpal vantagem em comparação com outros formatos de imagem usados na Web é o tamanho bastante reduzido dos arquivos, o que permite que as páginas Web carreguem mais rapidamente e reduz o uso de largura de banda. Usar imagens WebP pode levar a aumentos consideráveis na velocidade da página. Se o seu aplicativo ou site estiver passando por problemas de desempenho ou aumento de tráfego, converter suas imagens pode ajudar a otimizar o desempenho das páginas.

      Neste tutorial, você usará a ferramenta de linha de comando cwebp para converter imagens para o formato WebP, criando scripts que irão ver e converter imagens em um diretório específico. Finalmente, você irá explorar duas maneiras de exibir imagens WebP aos seus visitantes.

      Pré-requisitos

      Trabalhar com imagens WebP não exige uma distribuição específica, mas vamos demonstrar como trabalhar com os software relevantes no Ubuntu 16.04 e CentOS 7. Para seguir este tutorial você precisará de:

      • Um servidor configurado com um usuário não raiz (non-root) de comando sudo. Para configurar um servidor Ubuntu 16.04, você pode seguir nosso Guia de configuração inicial de servidor Ubuntu 16.04. Se você quiser usar o CentOS, você pode configurar um servidor CentOS 7 com nossa Configuração Inicial de Servidor com tutorial CentOS.

      • O Apache instalado no seu servidor. Se você estiver usando o Ubuntu, você pode seguir o passo um do Como Instalar Linux, Apache, MySQL, pilha PHP (LAMP) no Ubuntu 16.04. Se você estiver usando o CentOS, então você deve seguir o passo um do Como Instalar Linux, Apache, MySQL, pilha PHP (LAMP) no CentOS 7. Certifique-se de ajustar as configurações do seu firewall para permitir o tráfego HTTP e HTTPS.

      • mod_rewrite instalado no seu servidor. Se você estiver usando o Ubuntu, você pode seguir nosso guia Como Manipular URLs com mod_rewrite para o Apache no Ubuntu 16.04. No CentOS 7 o mod_rewrite é instalado e ativado por padrão.

      Passo 1 — Instalando o cwebp e Preparando o Diretório de Imagens

      Nesta seção, instalaremos o software para converter imagens e criaremos um diretório com imagens para a finalidade de teste.

      No Ubuntu 16.04, você pode instalar o cwebp, um utilitário que comprime imagens no formato .webp, digitando:

      • sudo apt-get update
      • sudo apt-get install webp

      No CentOS 7, digite:

      • sudo yum install libwebp-tools

      Para criar um novo diretório de imagens chamado webp no diretório raiz do Apache Web (localizado por padrão em /var/www/html) digite:

      • sudo mkdir /var/www/html/webp

      Altere o proprietário deste diretório para o seu usuário sammy não raiz:

      • sudo chown sammy: /var/www/html/webp

      Para testar comandos, você pode baixar imagens JPEG e PNG gratuitas usando o wget. Esta ferramenta é instalada por padrão no Ubuntu 16.04; se você estiver usando o CentOS 7, você pode instalá-la digitando:

      A seguir, baixe as imagens teste usando os comandos seguintes:

      • wget -c "https://upload.wikimedia.org/wikipedia/commons/2/24/Junonia_orithya-Thekkady-2016-12-03-001.jpg?download" -O /var/www/html/webp/image1.jpg
      • wget -c "https://upload.wikimedia.org/wikipedia/commons/5/54/Mycalesis_junonia-Thekkady.jpg" -O /var/www/html/webp/image2.jpg
      • wget -c "https://cdn.pixabay.com/photo/2017/07/18/15/39/dental-care-2516133_640.png" -O /var/www/html/webp/logo.png

      Nota: estas imagens estão disponíveis para uso e redistribuição sob a licença Creative Commons Attribution-ShareAlike e o Public Domain Dedication.

      A maior parte do seu trabalho no próximo passo estará no diretório /var/www/html/webp, para o qual você pode se mover digitando:

      Com as imagens teste instaladas e o servidor Apache Web, mod_rewrite e cwebp instalados, você está pronto para ir para a conversão de imagens.

      Exibir imagens .webp para visitantes do site exige versões .webp de arquivos de imagem. Neste passo, você irá converter imagens JPEG e PNG para o formato .webp usando o cwebp. A sintaxe geral do comando se parece com essa:

      • cwebp image.jpg -o image.webp

      A opção -o especifica o caminho até o arquivo WebP.

      Uma vez que você ainda está no diretório /var/www/html/webp, você pode executar o comando a seguir para converter a image1.jpg em image1.webp e image2.jpg em image2.webp:

      • cwebp -q 100 image1.jpg -o image1.webp
      • cwebp -q 100 image2.jpg -o image2.webp

      Definir o fator de qualidade -q em 100 retém 100% da qualidade da imagem; se não especificado, o valor padrão é 75.

      A seguir, inspecione o tamanho das imagens JPEG e WebP usando o comando ls. A opção -l irá mostrar o formato de lista longa, que inclui o tamanho do arquivo e a opção -h irá garantir que ls imprima tamanhos legíveis para humanos:

      • ls -lh image1.jpg image1.webp image2.jpg image2.webp

      Output

      -rw-r--r-- 1 sammy sammy 7.4M Oct 28 23:36 image1.jpg -rw-r--r-- 1 sammy sammy 3.9M Feb 18 16:46 image1.webp -rw-r--r-- 1 sammy sammy 16M Dec 18 2016 image2.jpg -rw-r--r-- 1 sammy sammy 7.0M Feb 18 16:59 image2.webp

      O resultado do comando ls mostra que o tamanho da image1.jpg é de 7,4 MB, enquanto o tamanho da image1.webp é 3,9 MB. O mesmo se aplica à image2.jpg (16 MB) e image2.webp (7 MB). Estes arquivos têm quase metade do tamanho original.

      Para salvar os dados das imagens completos e originais durante a compressão, você pode usar a opção -lossless no lugar de -q. Esta é a melhor opção para manter a qualidade de imagens PNG. Para converter a imagem PNG baixada do passo 1, digite:

      • cwebp -lossless logo.png -o https://www.digitalocean.com/logo.webp

      O comando a seguir mostra que o tamanho sem perdas da imagem WebP (60 KB) é aproximadamente metade do tamanho da imagem PNG original (116 KB):

      • ls -lh logo.png https://www.digitalocean.com/logo.webp

      Output

      -rw-r--r-- 1 sammy sammy 116K Jul 18 2017 logo.png -rw-r--r-- 1 sammy sammy 60K Feb 18 16:42 https://www.digitalocean.com/logo.webp

      As imagens convertidas no diretório /var/www/html/webp são cerca de 50% menores do que suas equivalentes em JPEG e PNG. Na prática, as taxas de compressão podem ser diferentes, dependendo de certos fatores: a taxa de compressão da imagem original, o formato do arquivo, o tipo de conversão (com ou sem perdas), a porcentagem de qualidade e o seu sistema operacional. Conforme você for convertendo mais imagens, você poderá ver variações nas taxas de conversão relacionadas a esses fatores.

      Passo 3 — Convertendo Imagens JPEG e PNG em um Diretório

      Escrever um script irá simplificar o processo de conversão, eliminando o trabalho da conversão manual. Agora, vamos escrever um script de conversão que encontre arquivos JPEG e os converta para o formato WebP com 90% da qualidade, enquanto também converte arquivos PNG em imagens WeP sem perdas.

      Usando o nano ou seu editor favorito, crie o script webp-convert.sh no diretório home do seu usuário.

      A primeira linha do script se parecerá com esta:

      ~/webp-convert.sh

      find $1 -type f -and ( -iname "*.jpg" -o -iname "*.jpeg" )
      

      Esta linha tem os seguintes componentes:

      • find: este comando irá procurar por arquivos dentro de um diretório especificado.
      • $1: este parâmetro posicional especifica o caminho do diretório de imagens, tirado da linha de comando. Em última análise, ele torna o local do diretório menos dependente do local do script.
      • -type f: esta opção diz ao find para procurar apenas arquivos regulares.
      • -iname: este teste compara os nomes dos arquivos com um padrão especificado. O teste -iname que não diferencia maiúsculas de minúsculas diz ao find para procurar qualquer nome de arquivo que termine com .jpg (*.jpg) ou .jpeg (*.jpeg).
      • -o: Este operador lógico instrui o comando find para listar arquivos que correspondam ao primeiro teste -iname (-iname ".jpg"**) ou o segundo (-iname "*.jpeg"**).
      • (): parênteses em volta desses testes, junto com o operador -and, garante que o primeiro teste (ou seja -type f) seja sempre executado.

      A segunda linha do script irá converter as imagens para WebP usando o parâmetro -exec. A sintaxe geral deste parâmetro é -exec command {} ;. Cada arquivo substitui uma string {}; o comando faz a iteração através desses arquivos, ao passo que a string ; diz para o find onde o comando termina:

      ~/webp-convert.sh

      find $1 -type f -and ( -iname "*.jpg" -o -iname "*.jpeg" ) 
      -exec bash -c 'commands' {} ;
      

      Neste caso, o parâmetro -exec irá exigir mais de um comando para procurar e converter imagens:

      • bash: este comando irá executar um pequeno script que irá criar a versão .webp do arquivo se ele não existir. Este script será passado para o bash como uma string, graças à opção -c.
      • 'commands': este espaço reservado é o script que irá fazer versões .webp dos seus arquivos.

      O script dentro de 'commands' fará as seguintes coisas:

      • Criar uma variável webp_path.
      • Testar se a versão .webp do arquivo existe ou não.
      • Criar o arquivo se ele não existir.

      O script menor se parece com este:

      ~/webp-convert.sh

      ...
      webp_path=$(sed 's/.[^.]*$/.webp/' <<< "$0");
      if [ ! -f "$webp_path" ]; then 
        cwebp -quiet -q 90 "$0" -o "$webp_path";
      fi;
      

      Os elementos neste script menor incluem:

      • webp_path: esta variável será gerada usando o sed e o nome do arquivo correspondente do comando bash, estipulado pelo pelo parâmetro posicional $0. Uma _string here_ (​​​​​​<<<) passará este nome para o sed.
      • if [ ! -f "$webp_path" ]: este teste irá determinar se um arquivo chamado "$webp_path" já existe, usando o operador lógico not (!).
      • cwebp: este comando irá criar o arquivo se ele não existir, usando a opção -q para não imprimir o resultado.

      Com este script menor no lugar do espaço reservado 'commands', o script completo para converter imagens JPEG se parecerá agora com este:

      ~/webp-convert.sh

      # converting JPEG images
      find $1 -type f -and ( -iname "*.jpg" -o -iname "*.jpeg" ) 
      -exec bash -c '
      webp_path=$(sed 's/.[^.]*$/.webp/' <<< "$0");
      if [ ! -f "$webp_path" ]; then 
        cwebp -quiet -q 90 "$0" -o "$webp_path";
      fi;' {} ;
      

      Para converter imagens PNG para WebP, vamos adotar a mesma abordagem, com duas diferenças: primeiro, o padrão -iname no comando find será "*.png". Segundo, o comando de conversão usará a opção -lossless em vez da opção de qualidade -q.

      O script final se parece com este:

      ~/webp-convert.sh

      #!/bin/bash
      
      # converting JPEG images
      find $1 -type f -and ( -iname "*.jpg" -o -iname "*.jpeg" ) 
      -exec bash -c '
      webp_path=$(sed 's/.[^.]*$/.webp/' <<< "$0");
      if [ ! -f "$webp_path" ]; then 
        cwebp -quiet -q 90 "$0" -o "$webp_path";
      fi;' {} ;
      
      # converting PNG images
      find $1 -type f -and -iname "*.png" 
      -exec bash -c '
      webp_path=$(sed 's/.[^.]*$/.webp/' <<< "$0");
      if [ ! -f "$webp_path" ]; then 
        cwebp -quiet -lossless "$0" -o "$webp_path";
      fi;' {} ;
      

      Salve o arquivo e saia do editor.

      Em seguida, vamos colocar o script webp-convert.sh em prática, usando os arquivos no diretório /var/www/html/webp. Certifique-se de que o arquivo script é executável, executando o comando a seguir:

      • chmod a+x ~/webp-convert.sh

      Execute o script no diretório de imagens:

      • ./webp-convert.sh /var/www/html/webp

      Nada aconteceu! Isso se dá porque já convertemos essas imagens no passo 2. Avançando, o script webp-convert converterá imagens quando adicionarmos novos arquivos ou removermos as versões .webp. Para ver como isso funciona, exclua os arquivos .webp que criamos no passo 2:

      • rm /var/www/html/webp/*.webp

      Após excluir todas as imagens .webp, execute o script novamente para garantir que ele funciona:

      • ./webp-convert.sh /var/www/html/webp

      O comando ls confirmará que o script converteu as imagens com sucesso:

      • ls -lh /var/www/html/webp

      Output

      -rw-r--r-- 1 sammy sammy 7.4M Oct 28 23:36 image1.jpg -rw-r--r-- 1 sammy sammy 3.9M Feb 18 16:46 image1.webp -rw-r--r-- 1 sammy sammy 16M Dec 18 2016 image2.jpg -rw-r--r-- 1 sammy sammy 7.0M Feb 18 16:59 image2.webp -rw-r--r-- 1 sammy sammy 116K Jul 18 2017 logo.png -rw-r--r-- 1 sammy sammy 60K Feb 18 16:42 https://www.digitalocean.com/logo.webp

      O script neste passo é a base para usar imagens WebP no seu site, uma vez que você precisará de uma versão m funcionamento de todas as imagens no formato WebP para exibir aos visitantes. O próximo passo abordará como automatizar a conversão de novas imagens.

      Passo 4 — Monitorando Arquivos de Imagem em um Diretório

      Neste passo, criaremos um novo script para monitorar nosso diretório de imagens quanto a alterações e para converter automaticamente as imagens recém-criadas.

      Criar um script que monitora nosso diretório de imagens pode resolver certos problemas com o script webp-convert.sh da forma como ele está escrito. Por exemplo, este script não identificará se renomeamos uma imagem. Se tivéssemos uma imagem chamada foo.jpg, executássemos o webp-convert.sh, renomeássemos aquele arquivo para bar.jpg e, então, executássemos o webp-convert.sh novamente, teríamos arquivos duplicados de .webp (foo.webp e bar.webp). Para resolver este problema e para evitar executar o script manualmente, adicionaremos observadores a outro script. Os observadores monitoram os arquivos ou diretórios especificados quanto às alterações e executam comandos em resposta a essas alterações.

      O comando inotifywait irá configurar observadores no nosso script. Este comando faz parte do pacote inotify-tools, um conjunto de ferramentas de linha de comando que fornecem uma interface simples ao subsistema do kernel inotify. Para instalá-lo no Ubuntu 16.04 digite:

      • sudo apt-get install inotify-tools

      Com o CentOS 7, o pacote inotify-tools está disponível no repositório EPEL. Instale o repositório EPEL e o pacote inotify-tools usando os comandos a seguir:

      • sudo yum install epel-release
      • sudo yum install inotify-tools

      Em seguida, crie o script webp-watchers.sh no diretório home do seu usuário usando o nano:

      A primeira linha do script se parecerá com esta:

      ~/webp-watchers.sh

      inotifywait -q -m -r --format '%e %w%f' -e close_write -e moved_from -e moved_to -e delete $1
      

      Esta linha inclui os seguintes elementos:

      • inotifywait: este comando monitora quanto às alterações em um certo diretório.
      • -q: esta opção irá dizer ao inotifywait para ficar quieto e não produzir grande quantidade de resultados.
      • -m: esta opção irá dizer ao inotifywait para executar indefinidamente e não sair após receber um único evento.
      • -r: esta opção irá configurar observadores de maneira repetitiva, monitorando um diretório especificado e todos os seus subdiretórios.
      • --format: esta opção diz ao inotifywait para monitorar alterações usando o nome do evento seguido do caminho do arquivo. Os eventos que queremos monitorar são close_write (acionado quando um arquivo é criado e completamente gravado no disco), moved_from e moved_to (acionados quando um arquivo é movido) e delete (acionado quando um arquivo é excluído).
      • $1: este parâmetro posicional retém o caminho dos arquivos alterados.

      Na sequência, vamos adicionar um comando grep para determinar se nossos arquivos são imagens JPEG ou PNG. A opção -i irá dizer ao grep para ignorar a diferença entre maiúsculas e minúsculas; -E irá especificar que o grep deve usar expressões regulares estendidas e a --line-buffered irá dizer ao grep para passar as linhas correspondentes para um loop while:

      ~/webp-watchers.sh

      inotifywait -q -m -r --format '%e %w%f' -e close_write -e moved_from -e moved_to -e delete $1 | grep -i -E '.(jpe?g|png)$' --line-buffered
      

      A seguir, vamos construir um loop while com o comando read. O read irá processar o evento que o inotifywait detectou, atribuindo-o a uma variável chamada $operation e o caminho do arquivo processado para uma variável chamada $path:

      ~/webp-watchers.sh

      ...
      | while read operation path; do
        # commands
      done;
      

      Vamos combinar este loop com o resto do nosso script:

      ~/webp-watchers.sh

      inotifywait -q -m -r --format '%e %w%f' -e close_write -e moved_from -e moved_to -e delete $1 
      | grep -i -E '.(jpe?g|png)$' --line-buffered 
      | while read operation path; do
        # commands
      done;
      

      Após o loop while verificar o evento, os comandos dentro do loop tomarão as seguintes ações, dependendo do resultado:

      • Criar um novo arquivo WebP se um novo arquivo de imagem for criado ou movido para o diretório de destino.
      • Excluir o arquivo WebP se o arquivo de imagem associado for excluído ou movido do diretório de destino.

      Há três seções principais dentro do loop. Uma variável chamada webp_path irá reter o caminho para a versão .webp da imagem em questão:

      ~/webp-watchers.sh

      ...
      webp_path="$(sed 's/.[^.]*$/.webp/' <<< "$path")";
      

      A seguir, o script irá testar qual evento aconteceu:

      ~/webp-watchers.sh

      ...
      if [ $operation = "MOVED_FROM" ] || [ $operation = "DELETE" ]; then
        # commands to be executed if the file is moved or deleted
      elif [ $operation = "CLOSE_WRITE,CLOSE" ] || [ $operation = "MOVED_TO" ]; then
        # commands to be executed if a new file is created
      fi;
      

      Se o arquivo foi movido ou excluído, o script irá verificar se a versão .webp existe. Se ela existe, o script irá removê-la usando o rm:

      ~/webp-watchers.sh

      ...
      if [ -f "$webp_path" ]; then
        $(rm -f "$webp_path");
      fi;
      

      Para arquivos recém-criados, a compressão irá acontecer da seguinte forma:

      • Se o arquivo correspondente for uma imagem PNG, o script irá usar a compressão sem perdas.
      • Se não for, o script usará uma compressão com perdas com a opção -quality.

      Vamos adicionar os comandos cwebp que irão fazer este trabalho no script:

      ~/webp-watchers.sh

      ...
      if [ $(grep -i '.png$' <<< "$path") ]; then
        $(cwebp -quiet -lossless "$path" -o "$webp_path");
      else
        $(cwebp -quiet -q 90 "$path" -o "$webp_path");
      fi;
      

      Na íntegra, o arquivo webp-watchers.sh se parecerá com este:

      ~/webp-watchers.sh

      #!/bin/bash
      echo "Setting up watches.";
      
      # watch for any created, moved, or deleted image files
      inotifywait -q -m -r --format '%e %w%f' -e close_write -e moved_from -e moved_to -e delete $1 
      | grep -i -E '.(jpe?g|png)$' --line-buffered 
      | while read operation path; do
        webp_path="$(sed 's/.[^.]*$/.webp/' <<< "$path")";
        if [ $operation = "MOVED_FROM" ] || [ $operation = "DELETE" ]; then # if the file is moved or deleted
          if [ -f "$webp_path" ]; then
            $(rm -f "$webp_path");
          fi;
        elif [ $operation = "CLOSE_WRITE,CLOSE" ] || [ $operation = "MOVED_TO" ]; then  # if new file is created
           if [ $(grep -i '.png$' <<< "$path") ]; then
             $(cwebp -quiet -lossless "$path" -o "$webp_path");
           else
             $(cwebp -quiet -q 90 "$path" -o "$webp_path");
           fi;
        fi;
      done;
      

      Salve e feche o arquivo. Não se esqueça de torná-lo executável:

      • chmod a+x ~/webp-watchers.sh

      Vamos executar este script no diretório /var/www/html/webp em segundo plano, usando o &. Vamos também redirecionar os resultados padrão e os erros padrão para um ~/output.log, para armazenar os resultados em local prontamente disponível:

      • ./webp-watchers.sh /var/www/html/webp > output.log 2>&1 &

      Neste ponto, você converteu os arquivos JPEG e PNG em /var/www/html/webp para o formato WebP e configurou observadores para fazer esse trabalho, usando o script webp-watchers.sh. Agora é hora de explorar opções para entregar imagens WebP aos visitantes do seu site.

      Passo 5 — Exibindo Imagens WebP para Visitantes Usando Elementos HTML

      Neste passo, vamos explicar como exibir imagens WebP com elementos HTML. Neste ponto, devem haver versões .webp de cada uma das imagens teste JPEG e PNG no diretório /var/www/html/webp. Agora, podemos exibi-las para os navegadores compatíveis, usando ou os elementos HTML5 (<picture>) ou o módulo Apache mod_rewrite. Vamos usar elementos HTML neste passo.

      O elemento <picture> permite que você inclua imagens diretamente nas suas páginas Web e defina mais de uma fonte de imagens. Se seu navegador é compatível com o formato WebP, ele irá baixar a versão .webp do arquivo em vez da versão original, resultando em páginas Web sendo exibidas mais rapidamente. Vale dizer que o elemento <picture> é bem suportado em navegadores modernos compatíveis com o formato WebP.

      O elemento <picture> é um container com elementos <source> que <image> apontam para arquivos específicos. Se usarmos <source> para apontar para uma imagem .webp, o navegador verá se ele pode lidar com ela; caso contrário, ele retrocederá para o arquivo de imagem especificado no atributo src do elemento <source>.

      Vamos usar o arquivo logo.png do nosso diretório /var/www/html/webp, o qual convertemos para https://www.digitalocean.com/logo.webp, como um exemplo com <source>. Podemos usar o seguinte código HTML para exibir o https://www.digitalocean.com/logo.webp em qualquer navegador compatível com o formato WebP e o logo.png com navegadors não compatíveis com o WebP ou o elemento <picture>.

      Crie um arquivo HTML localizado em /var/www/html/webp/picture.html:

      • nano /var/www/html/webp/picture.html

      Adicione o código a seguir à página Web para exibir o https://www.digitalocean.com/logo.webp para navegadores compatíveis, usando o elemento <picture>:

      /var/www/html/webp/picture.html

      <picture>
        <source  type="image/webp">
        <img src="https://www.digitalocean.com/logo.png" alt="Site Logo">
      </picture>
      

      Salve e feche o arquivo.

      Para testar se tudo está funcionando, navegue até a página http://your_server_ip/webp/picture.html. Você deve ver a imagem teste PNG.

      Agora que você sabe como exibir imagens .webp diretamente do código HTML, vamos ver como automatizar este processo usando o módulo mod_rewrite do Apache.

      Passo 6 — Exibindo Imagens WebP Usando o mod_rewrite

      Se queremos otimizar a velocidade do nosso site, mas temos um grande número de páginas ou muito pouco tempo para editar o código HTML, então o módulo mod_rewrite do Apache pode nos ajudar a automatizar o processo de exibição de imagens .webp em navegadores compatíveis.

      Primeiramente, crie um arquivo .htaccess no diretório /var/www/html/webp usando o comando a seguir:

      • nano /var/www/html/webp/.htaccess

      A diretiva ifModule irá testar se o mod_rewrite está disponível; se ele estiver, ele pode ser ativado usando o RewriteEngine On. Adicione essas diretivas ao .htaccess:

      /var/www/html/webp/.htaccess

      <ifModule mod_rewrite.c>
        RewriteEngine On 
        # further directives
      </IfModule>
      

      O servidor Web fará vários testes para estabelecer quando exibir imagens .webp para o usuário. Quando um navegador faz um pedido, ele inclui um cabeçalho que indica ao servidor o que o navegador é capaz de manipular. No caso do WebP, o navegador irá enviar um cabeçalho Accept que contém image/webp. Vamos verificar se o navegador enviou aquele cabeçalho usando o RewriteCond, que especifica os critérios que devem ser correspondidos para executar o RewriteRule:

      /var/www/html/webp/.htaccess

      ...
      RewriteCond %{HTTP_ACCEPT} image/webp
      

      Tudo deve ser filtrado, exceto as imagens JPEG e PNG. Usando o RewriteCond novamente, adicione uma expressão regular (similar ao que usamos nas seções anteriores) para corresponder ao URI solicitado:

      /var/www/html/webp/.htaccess

      ...
      RewriteCond %{REQUEST_URI}  (?i)(.*)(.jpe?g|.png)$ 
      

      O modificador (?i) fará com que a correspondência não diferencie maiúsculas e minúsculas.

      Para verificar se a versão .webp do arquivo existe, use o RewriteCond novamente do seguinte modo:

      /var/www/html/webp/.htaccess

      ...
      RewriteCond %{DOCUMENT_ROOT}%1.webp -f
      

      Finalmente, se todas as condições anteriores forem cumpridas, o RewriteRule irá redirecionar o arquivo JPEG ou PNG solicitado para seu arquivo WebP associado. Observe que isso irá redirecionar usando o sinalizador -R, em vez de reescrever o URI. A diferença entre reescrever e redirecionar é que o servidor irá exibir o URI reescrito sem contar ao navegador. Por exemplo, o URI irá mostrar que a extensão de arquivo é .png, mas ele será na realidade um arquivo .webp. Adicione o RewriteRule ao arquivo:

      /var/www/html/webp/.htaccess

      ...
      RewriteRule (?i)(.*)(.jpe?g|.png)$ %1.webp [L,T=image/webp,R] 
      

      Neste ponto, a seção mod_rewrite no arquivo .htaccess está completa. Mas o que acontecerá se houver um servidor de cache intermediário entre seu servidor e o cliente? Ele pode exibir a versão errada ao usuário final. É por isso que vale a pena verificar se o mod_headers está habilitado, para enviar o cabeçalho Vary: Accept. O cabeçalho Vary indica aos servidores de cache (como servidores proxy) que o tipo de conteúdo do documento varia dependendo das capacidades do navegador que solicita o documento. Além disso, a resposta será gerada com base no cabeçalho Accept no pedido. Um pedido com um cabeçalho Accept diferente pode obter uma resposta diferente. Este cabeçalho é importante porque ele impede que imagens WebP em cache sejam exibidas para navegadores não compatíveis:

      /var/www/html/webp/.htaccess

      ...
      <IfModule mod_headers.c>
        Header append Vary Accept env=REDIRECT_accept
      </IfModule>
      

      Enfim, no final do arquivo .htaccess, configure o tipo MIME das imagens .webp como image/webp usando a diretiva AddType. Isso irá exibir as imagens usando o tipo de MIME correto:

      /var/www/html/webp/.htaccess

      ...
      AddType image/webp .webp
      

      Esta é a versão final do nosso arquivo .htaccess:

      /var/www/html/webp/.htaccess

      <ifModule mod_rewrite.c>
        RewriteEngine On 
        RewriteCond %{HTTP_ACCEPT} image/webp
        RewriteCond %{REQUEST_URI}  (?i)(.*)(.jpe?g|.png)$ 
        RewriteCond %{DOCUMENT_ROOT}%1.webp -f
        RewriteRule (?i)(.*)(.jpe?g|.png)$ %1.webp [L,T=image/webp,R] 
      </IfModule>
      
      <IfModule mod_headers.c>
        Header append Vary Accept env=REDIRECT_accept
      </IfModule>
      
      AddType image/webp .webp
      

      Nota: você pode fundir este .htaccess com outro arquivo .htaccess, se ele existir. Se você está usando o WordPress, por exemplo, você deve copiar este arquivo .htaccess e colá-lo no topo do arquivo existente.

      Vamos colocar o que fizemos neste passo em prática. Se você seguiu as instruções nos passos anteriores, você deve ter as imagens logo.png e https://www.digitalocean.com/logo.webp em /var/www/html/webp. Vamos usar uma tag simples <img> para incluir a logo.png em nossa página Web. Crie um novo arquivo HTML para testar a configuração:

      • nano /var/www/html/webp/img.html

      Digite o código HTML a seguir no arquivo:

      /var/www/html/webp/img.html

      <img src="https://www.digitalocean.com/logo.png" alt="Site Logo">
      

      Salve e feche o arquivo.

      Quando você visitar a página Web usando o Chrome visitando http://your_server_ip/webp/img.html, você irá notar que a imagem exibida é a versão .webp (tente abrir a imagem em uma nova aba). Se você usa o Firefox, você receberá uma imagem .png automaticamente.

      Conclusão

      Neste tutorial, abordamos técnicas básicas para trabalhar com imagens WebP. Explicamos como usar o cwebp para converter arquivos, além de duas opções para exibir essas imagens aos usuários: o elemento <picture> do HTML5 e o mod_rewrite do Apache.

      Para personalizar os scripts deste tutorial, você pode consultar alguns desses recursos:

      • Para aprender mais sobre as características do formato WebP e como usar as ferramentas de conversão, consulte a documentação do WebP.
      • Para ver mais detalhes sobre o uso do elemento <picture>, consulte sua documentação no MDN.
      • Para entender completamente como usar o mod_rewrite, consulte sua documentação.

      Usar o formato WebP para suas imagens irá reduzir os tamanhos dos arquivos de maneira considerável. Isso pode reduzir o uso da largura de banda e fazer as páginas carregarem mais rapidamente, particularmente se seu site usar muitas imagens.



      Source link