This topic shows you how to install an SSL certificate on a Python Flask development server. You will learn how to download and upload certificate files, configure them in your Flask application, and verify the installation.
Usage notes
Before you begin, make sure that you meet the following requirements:
Certificate status: You have an SSL certificate issued by a trusted certificate authority. If the certificate is about to expire or has expired, you must first renew the SSL certificate.
Domain name matching: Make sure that the certificate matches all domain names that you want to secure. To add or modify domain names, you can Purchase a commercial certificate or Append and replace domain names.
Exact-match domain name: Applies only to the specified domain.
example.comprotects onlyexample.com.www.example.comprotects onlywww.example.com.
Wildcard domain name: Applies only to its first-level subdomains.
*.example.comapplies to first-level subdomains such aswww.example.comanda.example.com.*.example.comdoes not protect the root domainexample.comor multi-level subdomains such asa.b.example.com.
NoteTo match multi-level subdomains, the Bound Domains field must contain the exact domain, such as
a.b.example.com, or a corresponding wildcard domain, such as*.b.example.com.Server permissions: You need a
rootaccount or an account withsudoprivileges.Domain name resolution: The domain's DNS record is configured and resolves to the server's public IP address.
Environment dependencies: Python and Flask are installed on the server. This topic uses a Linux operating system, Python 3.6, and Flask 2.0.3 as an example.
Procedure
Step 1: Prepare the SSL certificate
Go to the SSL Certificate Management page. Find the target certificate, and click Download Certificate in the Actions column. On the Download tab, download the certificate for the Server Type Other.
Unzip the downloaded certificate package:
If the package contains a certificate file (.pem) and a private key file (.key), save both files. You will need them for deployment.
If the package contains only a certificate file (.pem) and not a private key file (.key), you must deploy the certificate with the private key file that you saved locally.
NoteIf you used a tool such as OpenSSL or Keytool to generate a Certificate Signing Request (CSR) file when applying for a certificate, the private key file was saved only on your local machine. The downloaded certificate package does not include the private key. If the private key is lost, the certificate is unusable. You must purchase a commercial certificate again and generate a new CSR and private key.
Step 2: Configure the system and network environment
Ensure your security group and system firewall allow inbound traffic on the HTTPS port (443).
Run the following command in the server terminal to check whether port 443 is open:
RHEL/CentOS
command -v nc > /dev/null 2>&1 || sudo yum install -y nc # Replace <your_server_public_ip> with the public IP address of your server. sudo ss -tlnp | grep -q ':443 ' || sudo nc -l 443 & sleep 1; nc -w 3 -vz <your_server_public_ip> 443If the output is
Ncat: Connected to <your_server_public_ip>:443, port 443 is open. Otherwise, open port 443 in the security group and firewall.Debian/Ubuntu
command -v nc > /dev/null 2>&1 || sudo apt-get install -y netcat # Replace <your_server_public_ip> with the public IP address of your server. sudo ss -tlnp | grep -q ':443 ' || sudo nc -l -p 443 & sleep 1; nc -w 3 -vz <your_server_public_ip> 443If the output is
Connection to <your_server_public_ip> port [tcp/https] succeeded!or[<your_server_public_ip>] 443 (https) open, port 443 is open. Otherwise, open port 443 in the security group and firewall.Open port 443 in your security group configuration.
ImportantIf your server is deployed on a cloud platform, make sure that its security group allows inbound traffic on TCP port 443. Otherwise, the service will be inaccessible. The following steps use Alibaba Cloud ECS as an example. For other cloud platforms, refer to their official documentation.
Go to the Elastic Compute Service (ECS) instances page and click the target instance name to go to the instance details page. For more information, see Add a security group rule to add a rule in the Security Group section with Authorization Policy set to Allow, Protocol Type to TCP, Destination Port Range to HTTPS (443), and Authorization Object to Anywhere (0.0.0.0/0).
Open port 443 in your firewall.
Run the following command to identify the active firewall service on your system:
if command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet firewalld; then echo "firewalld" elif command -v ufw >/dev/null 2>&1 && sudo ufw status | grep -qw active; then echo "ufw" elif command -v nft >/dev/null 2>&1 && sudo nft list ruleset 2>/dev/null | grep -q 'table'; then echo "nftables" elif command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet iptables; then echo "iptables" elif command -v iptables >/dev/null 2>&1 && sudo iptables -L 2>/dev/null | grep -qE 'REJECT|DROP|ACCEPT'; then echo "iptables" else echo "none" fiIf the output is
none, no further action is required. Otherwise, run the corresponding command below based on the output (firewalld,ufw,nftables, oriptables) to open port 443:firewalld
sudo firewall-cmd --permanent --add-port=443/tcp && sudo firewall-cmd --reloadufw
sudo ufw allow 443/tcpnftables
sudo nft add table inet filter 2>/dev/null sudo nft add chain inet filter input '{ type filter hook input priority 0; }' 2>/dev/null sudo nft add rule inet filter input tcp dport 443 counter accept 2>/dev/nulliptables
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPTTo make sure that the iptables rules persist after a system reboot, run the following commands:
RHEL/CentOS
sudo yum install -y iptables-services sudo service iptables saveDebian/Ubuntu
sudo apt-get install -y iptables-persistent sudo iptables-save | sudo tee /etc/iptables/rules.v4 >/dev/null
Step 3: Install the certificate in your Flask application
Run the following command to create a directory to store your certificate in the root (
/) directory of your server.mkdir /ssl # Create a certificate directory named ssl.Upload the certificate file and the private key file to the certificate directory (
/ssl).NoteYou can use the local file upload feature of a remote logon tool, such as PuTTY, XShell, or WinSCP, to upload files. If you are using an Alibaba Cloud Elastic Compute Service (ECS) instance, for more information about how to upload files, see Upload or download files.
Open the Flask application file and configure the certificate using the following example code.
The following is a complete Flask application code example. You can copy the code, modify the certificate paths, and save it as
test.pyto run a test.# Import the Flask web framework from flask import Flask app = Flask(__name__) @app.route("/") def main(): return "<p>Hello, World!</p>" # Configure the SSL certificate # The default port for HTTPS is 443. # Set the port to 443 and provide the absolute paths to your certificate and key files. # Replace '/ssl/cert.pem' with the absolute path of your certificate file. # Replace '/ssl/cert.key' with the absolute path of your private key file. context = (r'/ssl/cert.pem', r'/ssl/cert.key') app.run(host="0.0.0.0", port=443, ssl_context=context)Go to the directory that contains the
test.pyfile and run the following command to restart the Flask service.# test.py is used as an example. Replace it with your actual filename. python test.py
Step 4: Verify the installation
Access your domain over HTTPS in a web browser. For example,
https://yourdomain. Replaceyourdomainwith your actual domain.If a lock icon appears in the browser's address bar, the certificate is deployed successfully. If you encounter access errors or the lock icon does not appear, clear your browser cache or try again in incognito (privacy) mode.

Starting from version 117, the
icon in the Chrome address bar has been replaced with a new
icon. Click this icon to view the lock information.
If the issue persists, see FAQ for troubleshooting.
Going live
When you deploy to a production environment, follow these best practices to enhance security, stability, and maintainability:
Run as a non-administrator user:
Create a dedicated, low-privilege system user for the application. Never run the application with an account that has administrator privileges.
NoteA recommended approach is to configure SSL at the gateway layer. This involves deploying the certificate on a Server Load Balancer (SLB) or a reverse proxy such as Nginx. The gateway terminates the HTTPS traffic and forwards the decrypted HTTP traffic to the backend application.
Externalize credential management:
Never hard-code passwords or other sensitive information in your code or configuration files. Use environment variables, Vault, or a cloud provider's key management service to inject credentials.
Enforce HTTP to HTTPS redirection:
Redirect all HTTP traffic to HTTPS to prevent man-in-the-middle attacks.
Configure modern TLS protocols:
Disable old and insecure protocols (such as SSLv3, TLSv1.0, and TLSv1.1) in your server configuration. Enable only TLSv1.2 and TLSv1.3.
Monitor certificates and automate renewal:
After you deploy the certificate, enable domain monitoring. Alibaba Cloud automatically checks the certificate validity period and sends renewal reminders before expiration to help you renew in a timely manner and avoid service interruption. For detailed instructions, see Purchase and enable public domain name monitoring.
FAQ
Why is my certificate not working or HTTPS inaccessible after installation or update?
This issue is often caused by one of the following configuration problems. Check them in order:
Port 443 blocked: The server's security group or firewall does not have port 443 open. See Configure the system and network environment.
Domain mismatch: The domain you are accessing is not listed in the certificate's Bound Domains. See Domain name matching.
Flask not restarted: The Flask service was not restarted after the Flask application file was modified. For instructions, see Stop and restart the Flask service.
Incorrect certificate configuration: The certificate files were not replaced correctly, or the certificate path is incorrect in the Flask configuration. Check the certificate configuration in the Flask application file and ensure that you are using the latest, valid certificate file.
Missing certificate on other services: If your domain uses services such as a Content Delivery Network (CDN), Server Load Balancer (SLB), or Web Application Firewall (WAF), the certificate must also be installed on those services. See Certificate deployment locations when traffic passes through multiple Alibaba Cloud services to complete the setup.
Incomplete deployment on multiple servers: If your domain's DNS resolves to multiple servers, the certificate must be installed on all of them.
For further troubleshooting, see Resolve certificate deployment issues based on browser error messages and SSL certificate deployment troubleshooting guide.
What is the correct way to update or replace an installed SSL certificate in Flask?
Back up old files: Back up the existing certificate files (.pem and .key) on your server.
Get new files: Download the new certificate and private key files from your Certificate Management Service console.
Replace files: Upload the new files to your server, overwriting the old ones. Ensure the new files have the exact same path and filename as the ones specified in your Flask configuration.
Restart Flask: Restart the Flask service to apply the new certificate.
A FileNotFoundError error occurs when starting the Flask application
This error usually indicates an incorrect file path. Check if the paths for the certificate and private key files provided in ssl_context are correct. Paths should be relative to the directory where you run the python <your-app-file>.py command, or you should use absolute paths.
The browser displays "ERR_SSL_PROTOCOL_ERROR" or the connection is reset
Check the following:
Ensure the certificate file and the private key file match.
Ensure the certificate file is a complete certificate chain (usually a
.pemfile). Certificate files downloaded from Alibaba Cloud already include the complete chain.Ensure the server's security group or firewall allows traffic on the HTTPS port (port
443in this example).