Home >Backend Development >PHP Tutorial >Making Your Website Faster and Safer with Cloudflare

Making Your Website Faster and Safer with Cloudflare

Jennifer Aniston
Jennifer AnistonOriginal
2025-02-08 11:05:13180browse

Cloudflare: A comprehensive guide to improving website speed and security

Cloudflare, derived from Project Honeypot, is a provider of DDoS detection and protection services that can reduce server pressure and speed up websites. It also offers the "always online" option, providing a simplified version of the website in case of a source server failure.

Making Your Website Faster and Safer with Cloudflare

What’s unique about Cloudflare is that it’s not as an acceleration/performance tool from the outset, but rather from a honeypot project designed to provide spam and hacker protection services. To this day, DDoS detection and protection are still one of Cloudflare's main selling points. Its algorithm records the visitor's IP address, payload, request resources, and request frequency to detect malicious visitors.

Because Cloudflare is located in a proxy location between the website and all incoming traffic, it can significantly relieve the pressure on the server that DDoS attacks cannot even reach the original website, as stated in the introduction. Cloudflare also offers the "always online" option, which caches a version of the user's website and provides a simplified version of the website when the source server fails (the original website returns a 5xx or 4xx error). It also has full page caching functionality.

Making Your Website Faster and Safer with Cloudflare

These features have huge advantages: they can save web servers struggling with high loads and provide developers with breathing space to solve the problem in the event of server errors.

Cloudflare also offers free services. Of course, there are premium packages, and some features (such as additional page rules) are paid for, but the scope of Cloudflare free tier alone is enough to make it worth learning about its pros and cons. Comparative benchmarks show that Cloudflare is at a moderate level in speed, but it's hard to say it's the most cost-effective CDN on the market.

Cloudflare settings

Setting up a website with Cloudflare is very simple. After registering at https://www.php.cn/link/6f7bc4baeb295716fa1dbbf64887fcff, we can add a new website. We see an introductory video when the system scans for IP and other details for a given domain. Once done, we will get a new domain name server that needs to be set up at our registrar.

Making Your Website Faster and Safer with Cloudflare

We need to register these domain name servers at our registrar and wait for the changes to spread on the Internet. This can take up to 24 hours.

This change means giving all our control over the domain to Cloudflare. This also means that if we have emails (MX records) on that domain, we need to transfer those records to Cloudflare. If we have any subdomains, we also need to set it to the corresponding A record in Cloudflare's dashboard.

All existing domain records set up at our domain registrar or hosting providers require movement/copying to Cloudflare.

Some hosting providers may simplify/automate this conversion process further.

Making Your Website Faster and Safer with Cloudflare

For each of our domain records, we have the option to simply let all traffic go directly through our servers—which means we can set exceptions for certain subdomains—or we can turn off all Cloudflare features—e.g. , when we make some changes on the website.

Making Your Website Faster and Safer with Cloudflare

Once we set up the domain, it's basically all the work needed outside of the Cloudflare dashboard. No more operations are required on the website itself or on the source server. All further tweaks are done on the Cloudflare website.

Encryption settings

SSL certificates are part of the Cloudflare free program. There are four SSL settings options that we can find under the Encryption tab of the dashboard.

  • Close – This speaks for itself. All traffic will be redirected to an unsafe protocol (http).
  • Flexible – Cloudflare will provide all our pages to the final visitors via https regardless of the protocol for our server and whether we have an existing SSL certificate on it. The connection from Cloudflare to the origin server will be made through an insecure connection.
  • Full - Cloudflare will communicate with your server via https, but will not verify the certificate on the source. Traffic from Cloudflare to visitors is provided via https.
  • Full be strict – Cloudflare will require a valid (non-self-signed) SSL certificate on the source server. Traffic from Cloudflare to visitors is provided via https.

With these settings, we need to make sure the setup is reasonable, as we have two layers between the end user and the server content, so the omission here will cause a redirect loop, or too many redirects will eventually slow down the website.

Cloudflare also offers the option to purchase custom certificates, which provides the option to upload custom/premium certificates for advanced users who need extra security or care about their market image. This is part of the advanced program.

Website Security

This is one area where Cloudflare shines: it offers unprecedented free value. Throughout the hosting space, DDoS protection is an advanced service that is not always available even for paid customers.

Cloudflare offers unlimited DDoS protection at the free tier, along with some other rather complex tools that protect websites at the infrastructure level before malicious traffic arrives. It provides a rate limit of - restrict access based on user-defined, customizable rules. It provides smart firewall rules, country blocking, browser integrity checking, verification code protection, and more.

Now, when botnets dominate the internet, newly installed websites or servers are sometimes overwhelmed by brute-force attempts within minutes of going live, when spammers automatically execute web comments and even without any intrusions, the recommender spam When email is also rampant, POST attacks and slow attacks using unconventional means are not uncommon. This protection can be successful or medium-sized websites.

There are also crawl protections that deny certain resources to certain visitors profiles, or obfuscate emails.

The premium package offers more options.

Speed ​​and Performance

By default, using Cloudflare, we can cache static content—JavaScript, fonts, stylesheets, and even images. We can set cache expiration rules. For various CMS systems, there are plugins that can connect to Cloudflare so that we can clear caches inside the website.

These static resources are "taken over" by Cloudflare's infrastructure after DNS setup and then served from their data center networks all over the world based on the visitor's location.

Resources can be cached (or fetched from source) based on the query string or the cache header set by our source server. For example, in PHP, we can set cache expiration like this:

<code>header('Cache-Control: max-age=3600');</code>

If this is not enough, we may need to delete the Pragma, Expires and Cache Control headers:

<code>header_remove('Pragma');
header_remove('Expires');
header_remove('Cache-Control');</code>

We can also do this at the server level. In nginx we will set these rules in virtual host block/file:

<code>if ($http_cookie ~* "some-cookie") {
    #removing headers that stop Cloudflare cloudflare from caching
    more_clear_headers 'Pragma';
    more_clear_headers 'Expires';
    more_clear_headers 'Cache-Control';
    add_header Cache-Control "no-cache, no-store, max-age=0";
}

location ~* "(!?.*some-url-path.*)" {
    #removing headers that stop Cloudflare cloudflare from caching
    more_clear_headers 'Pragma';
    more_clear_headers 'Expires';
    more_clear_headers 'Cache-Control';
    add_header Cache-Control "max-age=3600";
}</code>

Apache users will add something like this to their .htaccess file:

<code><ifmodule> mod_headers.c></ifmodule>
Header unset Pragma env=LONGCACHE
Header unset Expires env=LONGCACHE
Header set Cache-Control "max-age=3600" env=LONGCACHE</code>

Obviously, the above some-cookie and some-url-path need to be replaced with the correct values. These rules are also required for the page caching mentioned below.

We can choose to compress our CSS, JS and HTML. There is an option to use AMP for outgoing AMP links. There is also a betafunction Rocket Loader, which uses the browser's local storage asynchronously bundled and provides JS. However, be careful with this, as small errors in the order of loading resources can break your website.

Paying customers can use the Railgun function, which solves the main pain point of the cache system - dynamic content. It tries to speed up the delivery of dynamic content from the source server. It requires software to be installed on the source server and works by compressing the delivered content and " maintaining a single persistent connection for multiple simultaneous requests, eliminating network connection latency ". This is reminiscent of the multiplexing functionality of the HTTP/2 protocol – just here, between the origin server and Cloudflare.

Pro plan also has image compression/optimization, as well as Polish and Mirage mechanisms. Under the Traffic tab, there are Argo routing optimization and load balancing options across Cloudflare's global data centers.

Full page HTML cache

Full page caching means cache all output from our system—CMS, applications, blog systems, or any other content.

Under "Page Rules", there is a hidden gem that converts your Cloudflare account into a full cache system that can compete with professional solutions like Varnish - and due to global data centers - may outweigh it .

Making Your Website Faster and Safer with Cloudflare

Set the cache level rule to Cache all content Cache the entire HTML content of the website along with all other resources.

By sorting these rules we can implement complex caching/exclusion solutions and deliver even dynamically generated content with minimal delays. 15 times the first time byte (TTFB) improvement is not unheard of.

These rules support wildcards and need to be sorted by priority:

<code>header('Cache-Control: max-age=3600');</code>

If we use this rule in conjunction with the Bypass setting in the next image, we can distinguish between the parts of the website that need to be cached/omitted from the cache under different conditions - such as the management part, etc.

Making Your Website Faster and Safer with Cloudflare

If the page cache is working, we should see CF-Cache-Status: HIT in the response header of the browser inspector.

Paid customers have other caching options, or bypass caching based on cookies. Here, the cookie name can be set using wildcard characters, and the content can also be cached according to the device type.

These rules are more complex and not every type of website needs them. Free customers can use three page rules, but additional rules can be purchased.

HTTP/2 and server push

Making Your Website Faster and Safer with Cloudflare

HTTP/2 is available by default for both free and enterprise customers—a significant improvement to the HTTP/1.1 protocol—including:

  • Multiplexing – Multiple resources can be sent asynchronously within a single connection
  • Head compression
  • Server Push – The server predicts requests to resources and sends them before the browser even requests them.

Although it is recognized that the improvements and value of Cloudflare need to be judged on a case-by-case basis, it is fair to say that the value provided by Cloudflare (particularly its free tier) is firmly above average.

Conclusion

This article describes how to use and configure Cloudflare and websites to make it fast, reliable and DDoS-proof. This is not to say that CDN websites are impermeable. In fact, it brings new vulnerabilities.

This is a major problem for the European Internet when human errors lead to damage to Cloudflare services in the 2016 Swedish Telia network provider case. It is estimated that 6.2% of the top 1 million websites in the world use Cloudflare services.

Making Your Website Faster and Safer with Cloudflare

Anyway, we should not be afraid of CDN because of such an incident. They are rare and ultimately help build a stronger network.

FAQs on Making Your Website Faster and Safe with Cloudflare

What is Cloudflare and how does it work?

Cloudflare is a network infrastructure and website security company that provides content delivery network services, DDoS mitigation, Internet security and distributed domain name server services. It works by protecting and speeding up any online website. Once your website becomes part of the Cloudflare community, its network traffic is routed through its smart global network. They automatically optimize web page delivery so that your visitors get the fastest page loading time and best performance.

How does Cloudflare make my website faster?

Cloudflare enhances website speed through its Content Delivery Network (CDN). CDN is a server network located around the world that caches static content of websites such as images and CSS/JavaScript files. When users visit your website, static content is delivered from the nearest CDN server, reducing loading time.

How does Cloudflare protect my website?

Cloudflare protects your website from various threats, including SQL injection, DDoS attacks, and cross-site scripting attacks. It uses a range of security technologies, including Web Application Firewall (WAF), Secure SSL and Global CDN to protect your website.

What different plans does Cloudflare offer?

Cloudflare offers a range of plans to meet different needs. These include free plans, professional plans, business plans and corporate plans. Each plan offers different features and support levels, and the enterprise plan offers the most comprehensive feature set.

How does Cloudflare's image optimization work?

Cloudflare's image optimization feature (called Polish) reduces the file size of the image to increase page loading time. It provides two modes: lossless mode, which reduces file size without changing the image; lossy mode, which reduces file size by deleting some image data.

How does Cloudflare's mobile optimization work?

Cloudflare's mobile optimization (called Mirage) is designed to improve the performance of your website on your mobile device. It does this by delaying the loading of images, merging network connections, and providing images of appropriate size according to the device.

How to set up Cloudflare for my website?

Setting up Cloudflare involves creating a Cloudflare account, adding your website to the account, and updating the domain name server to point to Cloudflare. Once this is done, Cloudflare will start caching your website and serving it from its CDN.

What is Cloudflare's "always online" feature?

"Always Online" is a feature that keeps your website cached version online even if your source server fails. This means that even if there is a problem with your hosting provider, visitors can still access your website.

How does Cloudflare's SSL/TLS encryption enhance website security?

Cloudflare's SSL/TLS encryption protects the security of data when moving between your website and visitors. This prevents third parties from intercepting and reading data, thereby enhancing the security of the website.

What is Cloudflare's Argo Smart Routing?

Argo Smart Routing is a feature that improves website performance by routing visitors with the least congested and most reliable paths using Cloudflare's private network. This can reduce internet latency and packet loss, thereby improving the user experience.

All pictures retain their original format and location.

The above is the detailed content of Making Your Website Faster and Safer with Cloudflare. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn