How To Host a Website Using Cloudflare and Nginx on Ubuntu 20.04 | DigitalOcean (2022)

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

Introduction

Cloudflare is a service that sits between the visitor and the website owner’s server, acting as a reverse proxy for websites. Cloudflare provides a Content Delivery Network (CDN), as well as DDoS mitigation and distributed domain name server services.

Nginx is a popular web server responsible for hosting some of the largest and highest-traffic sites on the internet. It’s common for organizations to serve websites with Nginx and use Cloudflare as a CDN and DNS provider.

In this tutorial, you will secure your website served by Nginx with an Origin CA certificate from Cloudflare and then configure Nginx to use authenticated pull requests. The advantages of using this setup are that you benefit from Cloudflare’s CDN and fast DNS resolution while ensuring that all connections pass through Cloudflare. This prevents any malicious requests from reaching your server.

Prerequisites

To complete this tutorial, you’ll need the following:

  • One Ubuntu 20.04 server set up by following the Ubuntu 20.04 initial server setup guide, including a sudo non-root user and a firewall.
  • Nginx installed on your server. You can follow our guide on how to install Nginx on Ubuntu 20.04.
  • A Cloudflare account.
  • A registered domain added to your Cloudflare account that points to your Nginx server. Our guide on how to mitigate DDoS attacks against your website with Cloudflare can help you set this up. Our introduction to DNS terminology, components, and concepts can also provide assistance.
  • An Nginx Server Block configured for your domain, which you can do by following Step 5 of How To Install Nginx on Ubuntu 20.04.

Step 1 — Generating an Origin CA TLS Certificate

The Cloudflare Origin CA lets you generate a free TLS certificate signed by Cloudflare to install on your Nginx server. By using the Cloudflare generated TLS certificate you can secure the connection between Cloudflare’s servers and your Nginx server.

To generate a certificate with Origin CA, log in to your Cloudflare account in a web browser. Select the domain that you want to secure and navigate to the SSL/TLS section of your Cloudflare dashboard. From there, navigate to the Origin Server tab and click on the Create Certificate button:

How To Host a Website Using Cloudflare and Nginx on Ubuntu 20.04 | DigitalOcean (1)

Leave the default option of Generate private key and CSR with Cloudflare selected.

How To Host a Website Using Cloudflare and Nginx on Ubuntu 20.04 | DigitalOcean (2)

Click Next and you will see a dialog with the Origin Certificate and Private key. You need to transfer both the origin certificate and private key from Cloudflare to your server. For security reasons, the Private Key information will not be displayed again, so copy the key to your server before clicking Ok.

How To Host a Website Using Cloudflare and Nginx on Ubuntu 20.04 | DigitalOcean (3)

You’ll use the /etc/ssl directory on the server to hold the origin certificate and the private key files. The folder already exists on the server.

(Video) Secure Your Domain with NGINX Proxy Manager and CloudFlare (Including Uptime Kuma Demonstration)

First, copy the contents of the Origin Certificate displayed in the dialog box in your browser.

Then, on your server, open /etc/ssl/cert.pem in your preferred text editor:

  1. sudo nano /etc/ssl/cert.pem

Paste the certificate contents into the file. Then save and exit the editor. If you are using nano, press Ctrl+X, then when prompted, Y and then Enter.

Then return to your browser and copy the contents of the Private key. Open the file /etc/ssl/key.pem for editing:

  1. sudo nano /etc/ssl/key.pem

Paste the private key into the file, save the file, and exit the editor.

Note: Sometimes, when you copy the certificate and key from the Cloudflare dashboard and paste it into the relevant files on the server, blank lines are inserted. Nginx will treat such certificates and keys as invalid, so ensure that there are no blank lines in your files.

Warning: Cloudflare’s Origin CA Certificate is only trusted by Cloudflare and therefore should only be used by origin servers that are actively connected to Cloudflare. If at any point you pause or disable Cloudflare, your Origin CA certificate will throw an untrusted certificate error.

Now that you copied the key and certificate files to your server, you need to update the Nginx configuration to use them.

Step 2 — Installing the Origin CA Certificate in Nginx

In the previous section, you generated an origin certificate and private key using Cloudflare’s dashboard and saved the files to your server. Now you’ll update the Nginx configuration for your site to use the origin certificate and private key to secure the connection between Cloudflare’s servers and your server.

First, make sure that UFW will allow HTTPS traffic. Enable Nginx Full, which will open both port 80 (HTTP) and port 443 (HTTPS):

  1. sudo ufw allow 'Nginx Full'

Now reload UFW:

  1. sudo ufw reload

Finally, check that your new rules are allowed and that UFW is active:

  1. sudo ufw status

You will see an output like this:

(Video) How to Deploy a Node.js App on Ubuntu with PM2, NGINX and Cloudflare

Output

Status: activeTo Action From-- ------ ----OpenSSH ALLOW AnywhereNginx Full ALLOW AnywhereOpenSSH (v6) ALLOW Anywhere (v6)Nginx Full (v6) ALLOW Anywhere (v6)

Now you are ready to adjust your Nginx server block. Nginx creates a default server block during installation. Remove it if it still exists, as you’ve already configured a custom server block for your domain:

  1. sudo rm /etc/nginx/sites-enabled/default

Next, open the Nginx configuration file for your domain:

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

The file should look like this:

/etc/nginx/sites-available/your_domain

server { listen 80; listen [::]:80; root /var/www/your_domain/html; index index.html index.htm index.nginx-debian.html; server_name your_domain www.your_domain; location / { try_files $uri $uri/ =404; }}

You’ll modify the Nginx configuration file to do the following:

  • Listen on port 80 and redirect all requests to use https.
  • Listen on port 443 and use the origin certificate and private key added in the previous section.

Modify the file so it looks like the following:

/etc/nginx/sites-available/your_domain

server { listen 80; listen [::]:80; server_name your_domain www.your_domain; return 302 https://$server_name$request_uri;}server { # SSL configuration listen 443 ssl http2; listen [::]:443 ssl http2; ssl_certificate /etc/ssl/cert.pem; ssl_certificate_key /etc/ssl/key.pem; server_name your_domain www.your_domain; root /var/www/your_domain/html; index index.html index.htm index.nginx-debian.html; location / { try_files $uri $uri/ =404; }}

Save the file and exit the editor.

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

  1. sudo nginx -t

If you found no problems, restart Nginx to enable your changes:

  1. sudo systemctl restart nginx

Now go to the Cloudflare dashboard’s SSL/TLS section, navigate to the Overview tab, and change SSL/TLS encryption mode to Full (strict). This informs Cloudflare to always encrypt the connection between Cloudflare and your origin Nginx server.

How To Host a Website Using Cloudflare and Nginx on Ubuntu 20.04 | DigitalOcean (4)

(Video) Using Nginx to Host Multiple Websites on One Server

Now visit your website at https://your_domain to verify that it’s set up properly. You’ll see your home page displayed, and the browser will report that the site is secure.

How To Host a Website Using Cloudflare and Nginx on Ubuntu 20.04 | DigitalOcean (5)

In the next section, you will set up Authenticated Origin Pulls to verify that your origin server is indeed talking to Cloudflare and not some other server. By doing so, Nginx will be configured to only accept requests that use a valid client certificate from Cloudflare; all requests that have not passed through Cloudflare will be dropped.

Step 3 — Setting Up Authenticated Origin Pulls

The Origin CA certificate will help Cloudflare verify that it is talking to the correct origin server. This step will use TLS Client Authentication to verify that your origin Nginx server is talking to Cloudflare.

In a client-authenticated TLS handshake, both sides provide a certificate to be verified. The origin server is configured to only accept requests that use a valid client certificate from Cloudflare. Requests which have not passed through Cloudflare will be dropped as they will not have Cloudflare’s certificate. This means that attackers cannot circumvent Cloudflare’s security measures and directly connect to your Nginx server.

Cloudflare presents certificates signed by a CA with the following certificate:

-----BEGIN CERTIFICATE-----MIIGCjCCA/KgAwIBAgIIV5G6lVbCLmEwDQYJKoZIhvcNAQENBQAwgZAxCzAJBgNVBAYTAlVTMRkwFwYDVQQKExBDbG91ZEZsYXJlLCBJbmMuMRQwEgYDVQQLEwtPcmlnaW4gUHVsbDEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzETMBEGA1UECBMKQ2FsaWZvcm5pYTEjMCEGA1UEAxMab3JpZ2luLXB1bGwuY2xvdWRmbGFyZS5uZXQwHhcNMTkxMDEwMTg0NTAwWhcNMjkxMTAxMTcwMDAwWjCBkDELMAkGA1UEBhMCVVMxGTAXBgNVBAoTEENsb3VkRmxhcmUsIEluYy4xFDASBgNVBAsTC09yaWdpbiBQdWxsMRYwFAYDVQQHEw1TYW4gRnJhbmNpc2NvMRMwEQYDVQQIEwpDYWxpZm9ybmlhMSMwIQYDVQQDExpvcmlnaW4tcHVsbC5jbG91ZGZsYXJlLm5ldDCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAN2y2zojYfl0bKfhp0AJBFeV+jQqbCw3sHmvEPwLmqDLqynI42tZXR5y914ZB9ZrwbL/K5O46exd/LujJnV2b3dzcx5rtiQzso0xzljqbnbQT20eihx/WrF4OkZKydZzsdaJsWAPuplDH5P7J82q3re88jQdgE5hqjqFZ3clCG7lxoBwhLaazm3NJJlUfzdk97ouRvnFGAuXd5cQVx8jYOOeU60sWqmMe4QHdOvpqB91bJoYQSKVFjUgHeTpN8tNpKJfb9LIn3pun3bC9NKNHtRKMNX3Kl/sAPq7q/AlndvA2Kw3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0bX1ZPpTpryXbvciVL5RkVBuyX2ntcOLDPlZWgxZCBp96x07FAnOzKgZk4RzZPNAxCXERVxajn/FLcOhglVAKo5H0ac+AitlQ0ip55D2/mf8o72tMfVQ6VpyjEXdiIXWUq/o=-----END CERTIFICATE-----

You can also download the certificate directly from Cloudflare’s documentation.

Copy this certificate.

Then create the file /etc/ssl/cloudflare.crt file to hold Cloudflare’s certificate:

  1. sudo nano /etc/ssl/cloudflare.crt

Add the certificate to the file. Then save the file and exit the editor.

Now update your Nginx configuration to use TLS Authenticated Origin Pulls. Open the configuration file for your domain:

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

Add the ssl_client_certificate and ssl_verify_client directives as shown in the following example:

/etc/nginx/sites-available/your_domain

(Video) Installing the NGINX web server in Ubuntu

. . .server { # SSL configuration listen 443 ssl http2; listen [::]:443 ssl http2; ssl_certificate /etc/ssl/cert.pem; ssl_certificate_key /etc/ssl/key.pem; ssl_client_certificate /etc/ssl/cloudflare.crt; ssl_verify_client on; . . .

Save the file and exit the editor.

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

  1. sudo nginx -t

If no problems were found, restart Nginx to enable your changes:

  1. sudo systemctl restart nginx

Finally, to enable Authenticated Pulls, open the SSL/TLS section in the Cloudflare dashboard, navigate to the Origin Server tab and toggle the Authenticated Origin Pulls option .

How To Host a Website Using Cloudflare and Nginx on Ubuntu 20.04 | DigitalOcean (6)

Now visit your website at https://your_domain to verify that it was set up properly. As before, you’ll see your home page displayed.

To verify that your server will only accept requests signed by Cloudflare’s CA, toggle the Authenticated Origin Pulls option to disable it and then reload your website. You should get the following error message :

How To Host a Website Using Cloudflare and Nginx on Ubuntu 20.04 | DigitalOcean (7)

Your origin server raises an error if Cloudflare’s CA does not sign a request.

Note: Most browsers will cache requests, so to see the above change you can use Incognito/Private browsing mode in your browser. To prevent Cloudflare from caching requests while you set up your website, navigate to Overview in the Cloudflare dashboard and toggle Development Mode.

Now that you know it works properly return to the SSL/TLS section in the Cloudflare dashboard, navigate to the Origin Server tab and toggle the Authenticated Origin Pulls option again to enable it.

Conclusion

In this tutorial, you secured your Nginx-powered website by encrypting traffic between Cloudflare and the Nginx server using an Origin CA certificate from Cloudflare. You then set up Authenticated Origin Pulls on the Nginx server to ensure that it only accepts Cloudflare servers’ requests, preventing anyone else from directly connecting to the Nginx server.

FAQs

How do I use Cloudflare with Nginx? ›

Step 1 — Generating an Origin CA TLS Certificate. The Cloudflare Origin CA lets you generate a free TLS certificate signed by Cloudflare to install on your Nginx server. By using the Cloudflare generated TLS certificate you can secure the connection between Cloudflare's servers and your Nginx server.

How do I host a website with Cloudflare? ›

Host Your Website on Cloudflare pages For Free | 2021 - YouTube

Does Cloudflare use Apache or Nginx? ›

We use NGINX for all of the web serving that we do. We use it as a reverse proxy on thousands of machines around the world.”

Does digital ocean use Cloudflare? ›

In July 2014, DigitalOcean became one of the first test customers of Cloudflare's new DNS proxy service, called DNS Firewall. With all of their DNS requests proxied and cached at Cloudflare's edge, DigitalOcean reliably serves several thousand DNS answers every second.

How do I host with nginx? ›

Host a Simple HTML Website on NGINX

As for Red Hat, as indicated on the NGINX test page, the default website root is /usr/share/nginx/html and this is where you should put your website content. Once you are in the default website root, run the command below to rename any existing index. html file.

Is Cloudflare a web server? ›

Fundamentally, Cloudflare is a large network of servers that can improve the security, performance, and reliability of anything connected to the Internet. Cloudflare does this by serving as a reverse proxy Open external link for your web traffic.

Is Cloudflare DNS free? ›

Is Cloudflare a free DNS (domain nameserver) provider? Yes. Cloudflare offers free DNS services to customers in all plans.

How do I host Cloudflare for free? ›

Free Options
  1. Add your Website or App to Cloudflare. Secure and accelerate personal websites with built-in, DNS, CDN, and DDoS protection.
  2. Protect Your Team with Cloudflare. Secure access to Internet, self-hosted and SaaS applications for up to 50 users for free.
  3. Deploy Serverless Code. ...
  4. Build and Deploy Modern Web Projects.

Which website builder works with Cloudflare? ›

Cloudflare is launching a new product today called Cloudflare Pages. It competes directly with Netlify or Vercel, two cloud hosting companies that let you build and deploy sites using JAMstack frameworks. Popular JAMstack frameworks include Gatsby, Jekyll, Hugo, Vue.

What server software does Cloudflare use? ›

CloudFlare uses a great deal of open source and free software. Our core server platform is nginx (which is released using a two-clause BSD license) and our primary database of choice is postgresql (which is released using their own BSD-like license).

Is NGINX a CDN? ›

NGINX is a high‑performance web server, load balancer, and proxy that our CDN network uses to deliver our customers' content as fast as possible. In the past few years, more high‑traffic websites have started using NGINX as their high‑performance server.

Is Cloudflare a reverse proxy? ›

Cloudflare is a service that acts as a reverse proxy between the website visitor and the server, providing DDoS mitigation as well as DNS and CDN services.

Is Cloudflare a cloud provider? ›

Cloudflare is an independent third party in any organization's cloud migration, minimizing the layers of lock-in between an organization and a cloud provider.

How does Cloudflare proxy work? ›

How it Works. Cloudflare acts as an intermediary between a client and a server, using a reverse proxy to mirror and cache websites. By storing web content for delivery on the closest edge server, it is able to optimize loading times.

How do I add a reverse proxy to Cloudflare? ›

Configure Cloudflare
  1. Configure Custom Domains with Self-Managed Certificates if you haven't already. ...
  2. Configure a CNAME setup with Cloudflare.
  3. Once Cloudflare has verified your domain, log in to the Cloudflare Dashboard.
  4. Create a new Cloudflare Page Rule with the following settings:

Is Cloudflare a reverse proxy? ›

Cloudflare is a service that acts as a reverse proxy between the website visitor and the server, providing DDoS mitigation as well as DNS and CDN services.

How does nginx reverse proxy work? ›

A reverse proxy server is a type of proxy server that typically sits behind the firewall in a private network and directs client requests to the appropriate backend server. A reverse proxy provides an additional level of abstraction and control to ensure the smooth flow of network traffic between clients and servers.

How does Cloudflare proxy work? ›

How it Works. Cloudflare acts as an intermediary between a client and a server, using a reverse proxy to mirror and cache websites. By storing web content for delivery on the closest edge server, it is able to optimize loading times.

Videos

1. How to Host Multiple Websites on One Public IP Address | Setting up an NginX Reverse Proxy Server
(Yeet PC)
2. Access Your Self Hosted Services WITHOUT Port Forwarding
(DB Tech)
3. Setting Up NextCloud on Docker w/ NGINX and CloudFlare for Remote Access!
(DB Tech)
4. NGINX Server Blocks | Host Multiple Websites On One Server With Single IP Address
(SnatchDreams)
5. Secure VPS in Ubuntu 20.04: LetsEncrypt, Cloudflare and more
(ProgramarYa - By JuanDMeGon)
6. Free SSL certificate for your website with CloudFlare. Full end to end encryption with free https
(Knowledge Sharing Tech)

Top Articles

Latest Posts

Article information

Author: Tish Haag

Last Updated: 12/07/2022

Views: 5996

Rating: 4.7 / 5 (47 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Tish Haag

Birthday: 1999-11-18

Address: 30256 Tara Expressway, Kutchburgh, VT 92892-0078

Phone: +4215847628708

Job: Internal Consulting Engineer

Hobby: Roller skating, Roller skating, Kayaking, Flying, Graffiti, Ghost hunting, scrapbook

Introduction: My name is Tish Haag, I am a excited, delightful, curious, beautiful, agreeable, enchanting, fancy person who loves writing and wants to share my knowledge and understanding with you.