flask配置https

原本flask起的服务只能在http访问,而https不行

做了以下配置之后可以用https访问了

下载snapd

$ sudo apt update
$ sudo apt install snapd

 下载apache

$ sudo apt-get install apache2

 下载certbot

$ sudo apt-get remove certbot
$ sudo snap install --classic certbot
$ sudo ln -s /snap/bin/certbot /usr/bin/certbot

配置 Let's Encrypt 证书 

$ sudo certbot --apache --apache-server-root /etc/apache2

另外一种方式配置 Let's Encrypt 证书 

engage@engage-project-vm:/etc/apache2/sites-available$ sudo openssl req -new -newkey rsa:2048 -nodes -keyout engage.key -out engage.csr
Generating a RSA private key
............................+++++
........+++++
writing new private key to 'engage.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:
State or Province Name (full name) [Some-State]:
Locality Name (eg, city) []:
Organization Name (eg, company) [Internet Widgits Pty Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:engage-2023.com
Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
engage@engage-project-vm:/etc/apache2/sites-available$ ls
000-default-le-ssl.conf  000-default.conf  default-ssl.conf  engage.csr  engage.key

使用新生成的CSR运行Certbot命令

engage@engage-project-vm:/etc/apache2/sites-available$ sudo certbot certonly --csr engage.csr 
Saving debug log to /var/log/letsencrypt/letsencrypt.log

How would you like to authenticate with the ACME CA?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: Apache Web Server plugin (apache)
2: Runs an HTTP server locally which serves the necessary validation files under
the /.well-known/acme-challenge/ request path. Suitable if there is no HTTP
server already running. HTTP challenge only (wildcards not supported).
(standalone)
3: Saves the necessary validation files to a .well-known/acme-challenge/
directory within the nominated webroot path. A seperate HTTP server must be
running and serving files from the webroot path. HTTP challenge only (wildcards
not supported). (webroot)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number [1-3] then [enter] (press 'c' to cancel): 1
Requesting a certificate for engage-2023.com

Successfully received certificate.
Certificate is saved at:            /etc/apache2/sites-available/0000_cert.pem
Intermediate CA chain is saved at:  /etc/apache2/sites-available/0000_chain.pem
Full certificate chain is saved at: /etc/apache2/sites-available/0001_chain.pem
This certificate expires on 2023-11-14.

NEXT STEPS:
- Certificates created using --csr will not be renewed automatically by Certbot. You will need to renew the certificate before it expires, by running the same Certbot command again.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
If you like Certbot, please consider supporting our work by:
 * Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
 * Donating to EFF:                    https://eff.org/donate-le
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  • 000-default-le-ssl.conf: Let's Encrypt为默认站点自动生成的SSL配置文件。
  • 000-default.conf: Apache的默认站点配置文件。
  • 0000_cert.pem: 最近从Let's Encrypt获取的证书。
  • 0000_chain.pem: 与的证书相关的中间证书链。
  • 0001_chain.pem: 完整的证书链,包括证书和中间证书。
  • default-ssl.conf: Apache默认的SSL虚拟主机配置文件模板。
  • engage.csr: 之前生成的证书签名请求(CSR)。
  • engage.key: 与CSR关联的私钥。
engage@engage-project-vm:/etc/apache2/sites-available$ ls
000-default-le-ssl.conf  000-default.conf  0000_cert.pem  0000_chain.pem  0001_chain.pem  default-ssl.conf  engage.csr  engage.key
# 000-default-le-ssl.conf 

<IfModule mod_ssl.c>
<VirtualHost *:443>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf


ServerName engage-2023.com
SSLProtocol TLSv1 TLSv1.1 TLSv1.2 TLSv1.3
SSLCertificateFile /etc/apache2/sites-available/0000_cert.pem
SSLCertificateKeyFile /etc/apache2/sites-available/engage.key
SSLCertificateChainFile /etc/apache2/sites-available/0001_chain.pem
# SSLCertificateFile /etc/letsencrypt/live/engage-2023.com/fullchain.pem
# SSLCertificateKeyFile /etc/letsencrypt/live/engage-2023.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf

        Alias /static/ "/home/engage/github_projects/socket/backend/static/"
        <Directory "/home/engage/github_projects/socket/backend/static/">
            Options +FollowSymlinks
            Require all granted
        </Directory>

ProxyPass /videos http://127.0.0.1:80/videos
ProxyPassReverse /videos http://127.0.0.1:80/videos

ProxyPass /video http://127.0.0.1:80/video
ProxyPassReverse /video http://127.0.0.1:80/video

ProxyPass /barrage http://127.0.0.1:5001/barrage
ProxyPassReverse /barrage http://127.0.0.1:5001/barrage

</VirtualHost>
</IfModule>

进入配置文件目录

$ cd /etc/apache2/sites-available/
$ ls
000-default-le-ssl.conf  000-default.conf  default-ssl.conf

添加路由代理

# 000-default-le-ssl.conf

<IfModule mod_ssl.c>
<VirtualHost *:443>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf


ServerName engage-2023.com
SSLCertificateFile /etc/letsencrypt/live/engage-2023.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/engage-2023.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf

        Alias /static/ "/home/engage/github_projects/socket/backend/static/"
        <Directory "/home/engage/github_projects/socket/backend/static/">
            Options +FollowSymlinks
            Require all granted
        </Directory>

ProxyPass /videos http://127.0.0.1:80/videos
ProxyPassReverse /videos http://127.0.0.1:80/videos

ProxyPass /video http://127.0.0.1:80/video
ProxyPassReverse /video http://127.0.0.1:80/video

ProxyPass /barrage http://127.0.0.1:5001/barrage
ProxyPassReverse /barrage http://127.0.0.1:5001/barrage

</VirtualHost>
</IfModule>

apache2端口配置在8080

# 000-default.conf

<VirtualHost *:8080>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
RewriteEngine on
RewriteCond %{SERVER_NAME} =engage-2023.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

配置 TLS 各个版本支持

# default-ssl.conf 

<IfModule mod_ssl.c>
        <VirtualHost _default_:443>
                ServerAdmin webmaster@localhost

                DocumentRoot /var/www/html

                # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
                # error, crit, alert, emerg.
                # It is also possible to configure the loglevel for particular
                # modules, e.g.
                #LogLevel info ssl:warn

                ErrorLog ${APACHE_LOG_DIR}/error.log
                CustomLog ${APACHE_LOG_DIR}/access.log combined

                # For most configuration files from conf-available/, which are
                # enabled or disabled at a global level, it is possible to
                # include a line for only one particular virtual host. For example the
                # following line enables the CGI configuration for this host only
                # after it has been globally disabled with "a2disconf".
                #Include conf-available/serve-cgi-bin.conf

                #   SSL Engine Switch:
                #   Enable/Disable SSL for this virtual host.
                SSLEngine on
                SSLEngine +TLS1.0 +TLS1.1 +TLS1.2 +TLS1.3

                #   A self-signed (snakeoil) certificate can be created by installing
                #   the ssl-cert package. See
                #   /usr/share/doc/apache2/README.Debian.gz for more info.
                #   If both key and certificate are stored in the same file, only the
                #   SSLCertificateFile directive is needed.
                SSLCertificateFile      /etc/ssl/certs/ssl-cert-snakeoil.pem
                SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key

                #   Server Certificate Chain:
                #   Point SSLCertificateChainFile at a file containing the
                #   concatenation of PEM encoded CA certificates which form the
                #   certificate chain for the server certificate. Alternatively
                #   the referenced file can be the same as SSLCertificateFile
                #   when the CA certificates are directly appended to the server
                #   certificate for convinience.
                #SSLCertificateChainFile /etc/apache2/ssl.crt/server-ca.crt

                #   Certificate Authority (CA):
                #   Set the CA certificate verification path where to find CA
                #   certificates for client authentication or alternatively one
                #   huge file containing all of them (file must be PEM encoded)
                #   Note: Inside SSLCACertificatePath you need hash symlinks
                #                to point to the certificate files. Use the provided
                #                Makefile to update the hash symlinks after changes.
                #SSLCACertificatePath /etc/ssl/certs/
                #SSLCACertificateFile /etc/apache2/ssl.crt/ca-bundle.crt

                #   Certificate Revocation Lists (CRL):
                #   Set the CA revocation path where to find CA CRLs for client
                #   authentication or alternatively one huge file containing all
                #   of them (file must be PEM encoded)
                #   Note: Inside SSLCARevocationPath you need hash symlinks
                #                to point to the certificate files. Use the provided
                #                Makefile to update the hash symlinks after changes.
                #SSLCARevocationPath /etc/apache2/ssl.crl/
                #SSLCARevocationFile /etc/apache2/ssl.crl/ca-bundle.crl

                #   Client Authentication (Type):
                #   Client certificate verification type and depth.  Types are
                #   none, optional, require and optional_no_ca.  Depth is a
                #   number which specifies how deeply to verify the certificate
                #   issuer chain before deciding the certificate is not valid.
                #SSLVerifyClient require
                #SSLVerifyDepth  10

                #   SSL Engine Options:
                #   Set various options for the SSL engine.
                #   o FakeBasicAuth:
                #        Translate the client X.509 into a Basic Authorisation.  This means that
                #        the standard Auth/DBMAuth methods can be used for access control.  The
                #        user name is the `one line' version of the client's X.509 certificate.
                #        Note that no password is obtained from the user. Every entry in the user
                #        file needs this password: `xxj31ZMTZzkVA'.
                #   o ExportCertData:
                #        This exports two additional environment variables: SSL_CLIENT_CERT and
                #        SSL_SERVER_CERT. These contain the PEM-encoded certificates of the
                #        server (always existing) and the client (only existing when client
                #        authentication is used). This can be used to import the certificates
                #        into CGI scripts.
                #   o StdEnvVars:
                #        This exports the standard SSL/TLS related `SSL_*' environment variables.
                #        Per default this exportation is switched off for performance reasons,
                #        because the extraction step is an expensive operation and is usually
                #        useless for serving static content. So one usually enables the
                #        exportation for CGI and SSI requests only.
                #   o OptRenegotiate:
                #        This enables optimized SSL connection renegotiation handling when SSL
                #        directives are used in per-directory context.
                #SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
                <FilesMatch "\.(cgi|shtml|phtml|php)$">
                                SSLOptions +StdEnvVars
                </FilesMatch>
                <Directory /usr/lib/cgi-bin>
                                SSLOptions +StdEnvVars
                </Directory>

                #   SSL Protocol Adjustments:
                #   The safe and default but still SSL/TLS standard compliant shutdown
                #   approach is that mod_ssl sends the close notify alert but doesn't wait for
                #   the close notify alert from client. When you need a different shutdown
                #   approach you can use one of the following variables:
                #   o ssl-unclean-shutdown:
                #        This forces an unclean shutdown when the connection is closed, i.e. no
                #        SSL close notify alert is send or allowed to received.  This violates
                #        the SSL/TLS standard but is needed for some brain-dead browsers. Use
                #        this when you receive I/O errors because of the standard approach where
                #        mod_ssl sends the close notify alert.
                #   o ssl-accurate-shutdown:
                #        This forces an accurate shutdown when the connection is closed, i.e. a
                #        SSL close notify alert is send and mod_ssl waits for the close notify
                #        alert of the client. This is 100% SSL/TLS standard compliant, but in
                #        practice often causes hanging connections with brain-dead browsers. Use
                #        this only for browsers where you know that their SSL implementation
                #        works correctly.
                #   Notice: Most problems of broken clients are also related to the HTTP
                #   keep-alive facility, so you usually additionally want to disable
                #   keep-alive for those clients, too. Use variable "nokeepalive" for this.
                #   Similarly, one has to force some clients to use HTTP/1.0 to workaround
                #   their broken HTTP/1.1 implementation. Use variables "downgrade-1.0" and
                #   "force-response-1.0" for this.
                # BrowserMatch "MSIE [2-6]" \
                #               nokeepalive ssl-unclean-shutdown \
                #               downgrade-1.0 force-response-1.0

        </VirtualHost>
</IfModule>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

https打开的默认页面软链接到自己服务器文件夹的页面文件

$ cd /var/www/html/
$ ll
total 24
drwxr-xr-x 2 root root  4096 Aug 15 09:50 ./
drwxr-xr-x 3 root root  4096 Aug 15 06:32 ../
lrwxrwxrwx 1 root root    76 Aug 15 09:50 index.html -> /home/engage/github_projects/socket/backend/RESTful/templates/videolist.html
-rw-r--r-- 1 root root 10918 Aug 15 06:32 index.html.backup

flask 源文件

# videolist.py

from flask import Flask, jsonify, abort,send_from_directory,render_template
from flask_cors import CORS,cross_origin
from flask import request
import json

app = Flask(__name__, static_folder='/home/engage/github_projects/socket/backend/static')
CORS(app)

@app.route('/videos', methods=['GET'])
@cross_origin()
def get_videos():
    try:
        with open('/home/engage/github_projects/socket/backend/RESTful/videos.json', 'r') as file:
            data = json.load(file)
            return jsonify(data)
    except FileNotFoundError:
        abort(404,description="video list file not found")
    except json.JSONDecodeError:
        abort(500,description="Error decoding file")


def get_video_url_by_vid(vid):
    with open('/home/engage/github_projects/socket/backend/RESTful/videos.json', 'r') as file:
        data = json.load(file)
        for video in data["videos"]:
            if video["vid"] == vid:
                return video["url"]
    return None


@app.route('/video')
@cross_origin()
def video_page():
    vid = request.args.get('vid')
    video_url = get_video_url_by_vid(vid)
    if video_url is None:
        abort(404, description="Video not found")
    return render_template('video_page.html', video_url=video_url,vid=vid)


@app.route('/')
@cross_origin()
def video_list():
    return render_template('videolist.html')

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=80,debug=True)
# barrage.py

from flask import Flask, jsonify, abort, request
from flask_cors import CORS, cross_origin
import json

app = Flask(__name__)
CORS(app)

BASE_PATH = '/home/engage/github_projects/socket/backend/static/movie'

@app.route('/barrage', methods=['GET'])
@cross_origin()
def manage_barrages():
    # 获取查询参数vid的值
    vid = request.args.get('vid')

    # 确保vid是一个数字
    if not vid or not vid.isdigit():
        abort(400, description="Invalid vid parameter")

    file_path = f"{BASE_PATH}{vid}/barrages.json"

    try:
        with open(file_path, 'r') as file:
            data = json.load(file)
            return jsonify(data)
    except FileNotFoundError:
        abort(404, description=f"Barrages file for movie{vid} not found")
    except json.JSONDecodeError:
        abort(500, description="Error decoding the barrages data")

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5001, debug=True)

服务执行命令

$ sudo nohup python3 videolist.py > videolist.log 2>&1 &
$ sudo nohup python3 barrage.py > barrage.log 2>&1 &
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在IIS上部署SSL证书,可以按照以下步骤进行操作: 1. 获取SSL证书:从可信的证书颁发机构(CA)或自己创建一个自签名证书。 2. 在IIS管理器中打开服务器节点,选择“服务器证书”功能。 3. 在右侧的“动作”面板中,选择“创建证书请求”。 4. 输入相关信息,如常用名称(域名)、组织名称等。确保填写的信息与您在证书颁发机构注册时提供的信息一致。 5. 选择一个保存位置,将生成的证书请求文件(.csr)保存到该位置。 6. 使用生成的证书请求文件去CA申请证书。根据CA的要求填写申请表格并提交请求。 7. 在收到由CA签名的SSL证书之后,打开IIS管理器中的服务器节点,选择“服务器证书”功能。 8. 在右侧的“动作”面板中,选择“完成证书请求”。 9. 在“完成证书请求”对话框中,选择您收到的证书文件,并为该证书指定一个友好名称。 10. 完成后,您将在“服务器证书”中看到已安装的SSL证书。 11. 转到您要启用SSL的网站节点,在网站节点上选择“绑定”功能。 12. 在“网站绑定”对话框中,选择协议为HTTPS,选择正确的IP地址和端口。 13. 在SSL证书下拉菜单中,选择您在步骤10中安装的SSL证书。 14. 点击“确定”完成绑定。 现在您的IIS服务器上已成功部署了SSL证书。请确保您的域名解析正确,并且将流量正确地重定向到HTTPS端口(通常为443)。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值