🔍 Introduction

When deploying a Flask web application, it's best practice to place it behind a reverse proxy to enhance security, enable SSL encryption, and optimize traffic handling. Nginx is a powerful web server that efficiently handles these tasks.

In this guide, we will:

  • Configure Nginx as a reverse proxy for a Flask application running on port 5000.
  • Secure the setup with a custom SSL certificate.
  • Automate the installation and configuration using Ansible on RHEL 8.

By the end, you’ll have a fully automated solution that ensures your Flask app is securely accessible over HTTPS.

---

🚀 Steps to Automate Installation Using Ansible

1️⃣ Install Nginx on RHEL 8

We need to install Nginx to act as a reverse proxy for our Flask app.

2️⃣ Copy SSL Certificates

The SSL certificate and private key must be placed in the correct directory.

3️⃣ Configure Nginx Reverse Proxy

We will create an Nginx configuration file to route traffic to our Flask application.

4️⃣ Enable and Start Nginx

Ensure that Nginx starts on boot and is running.

---

📝 Ansible Playbook

Create a new Ansible playbook named nginx_reverse_proxy.yml:

``yaml

---

  • name: Setup Nginx Reverse Proxy for Flask with SSL

hosts: webserver

become: true

vars:

domain_name: "example.com"

ssl_cert_path: "/etc/nginx/ssl/example.com.crt"

ssl_key_path: "/etc/nginx/ssl/example.com.key"

flask_app_port: 5000

tasks:

- name: Install Nginx

yum:

name: nginx

state: present

- name: Create SSL directory

file:

path: /etc/nginx/ssl

state: directory

owner: root

group: root

mode: '0755'

- name: Copy SSL certificate

copy:

src: files/example.com.crt

dest: "{{ ssl_cert_path }}"

owner: root

group: root

mode: '0644'

- name: Copy SSL key

copy:

src: files/example.com.key

dest: "{{ ssl_key_path }}"

owner: root

group: root

mode: '0600'

- name: Create Nginx reverse proxy config

template:

src: templates/flask_nginx.conf.j2

dest: /etc/nginx/conf.d/flask_app.conf

owner: root

group: root

mode: '0644'

notify:

- Restart Nginx

- name: Ensure Nginx is running and enabled

service:

name: nginx

state: started

enabled: yes

handlers:

- name: Restart Nginx

service:

name: nginx

state: restarted

`

---

🔧 Nginx Configuration Template

Create a Jinja2 template file named templates/flask_nginx.conf.j2:

``nginx

server {

listen 80;

server_name {{ domain_name }};

location / {

return 301 https://$host$request_uri;

}

}

server {

listen 443 ssl;

server_name {{ domain_name }};

ssl_certificate {{ ssl_cert_path }};

ssl_certificate_key {{ ssl_key_path