AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / server / 问题

问题[gunicorn](server)

Martin Hope
gigio
Asked: 2023-08-25 17:38:18 +0800 CST

部署在 URL 前缀后面时处理 Flask 路由路径

  • 5

我使用 python Flask框架构建单页应用程序。我使用Gunicorn作为 Web 服务器,并使用docker将其容器化。它通过Nginx Ingress Controller部署在Azure Kubernetes Services ( aks )上。

设置

我的 Flask 应用程序如下所示:

src/main.py

from flask import Flask
from src.routes import main_bp


app = Flask(__name__)
app.register_blueprint(main_bp)


@app.route('/health/live')
def healthLiveMsg():
    return 'Healthy'


@app.route('/health/ready')
def healthReadyMsg():
    return 'Healthy'


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)

src/main_bp.py

from flask import Blueprint, render_template


main_bp = Blueprint('main', __name__)

# home page
@main_bp.route('/')
def home():
    return render_template('index.html')

# some other page
@main_bp.route('/import')
def import_page():
    # some code...
    return renter_template('import.html')


# some backend job trigger
@main_bp.route('/run_job', methods=['POST'])
def run_job():
    # some code...    


def register_blueprints(app):
    app.register_blueprint(main_bp)

有base.html一个导航栏,我使用 Flask 的url_for功能分别获取主页和导入页面的链接href="{{ url_for('main.home') }},href="{{ url_for('main.import_page') }}

aks 入口在以下 yaml 模板中定义:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: __AksIngress__-ingress
  namespace: __AksNamespace__
  annotations:
    nginx.ingress.kubernetes.io/proxy-buffer-size: 16k
    nginx.ingress.kubernetes.io/proxy-body-size: "0"
    nginx.ingress.kubernetes.io/server-alias: __AksNamespace__.__AksDnsZone__.__AksDomainName__
    nginx.ingress.kubernetes.io/rewrite-target: /$1
    nginx.ingress.kubernetes.io/proxy-connect-timeout: "3600"
    nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "3600"
    nginx.ingress.kubernetes.io/server-snippet: keepalive_timeout 3600s;client_body_timeout 3600s;client_header_timeout 3600s;
spec:
  tls:
  - hosts:
    - __AksNamespace__.__AksDnsZone__.__AksDomainName__
    secretName: __AksIngress__-tls
  ingressClassName: nginx
  rules:
  - host: __AksNamespace__.__AksDnsZone__.__AksDomainName__
    http:
      paths:
      - path: /myapp/?(.*)
        pathType: Prefix
        backend:
          service:
            name: myapp-service
            port:
              number: 80

问题

当部署在 aks 上时,可以通过以下地址访问该应用程序example.com/myapp。所提供的页面显示导航栏的 html,其中包含hrefs as"/"和"/import"。当点击其中任何一个时,浏览器会导航到example.com并example.com/import删除myapp前缀,当然会出现 404 错误。我们期望在页面导航时正确构建 URL,并带有前缀,例如example.com/myapp/import。活性和就绪性检查(可在example.com/myapp/health/live和获取example.com/myapp/health/ready)由 Kubernetes 找到。

我的尝试

我尝试了多种解决方案,但没有一个有效。

SCRIPT_NAME

经过几次搜索后,我发现这篇博客文章提到了正确的解决方案。我在 dockerfile 中设置了环境变量并在本地计算机上运行容器,是的,它正在工作:

  • 主页位于localhost/myapp
  • 单击导航栏将我带到localhost/myapp/import
  • 单击导入页面中发布的按钮以localhost/myapp/run_job触发后端作业。

然而,部署到 aks 后,一切都只是多了一个额外的前缀:

  • 主页现在位于example.com/myapp/myapp
  • 导航到其他页面example.com/myapp/import时,我会看到该页面现在位于example.com/myapp/myapp/import
  • 类似的事情与run_job
  • 此外,kubernetes 的活性和就绪性检查失败,因为它们也在双前缀路径下。

代理修复

我尝试按照此 SO 答案中的建议使用 ProxyFix ,并在初始化应用程序后添加以下行:

app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_host=1)

然而,这似乎并没有产生任何效果。我也尝试过传递x_prefix=1参数,但没有成功。

问题

我读了很多东西,现在我已经很困惑了。我开始使用“flaskrouting with aks”作为关键词来搜索答案,然后转移到“wsgi服务器”,然后“nginx反向代理”“nginx前缀”或“nginx入口”,现在我不确定实际上是什么正在发生。我不确定解决方案是否应该来自ingress.yamlgunicorn,或者是否是需要适应的flask应用程序。

我看到的行为是什么以及如何解决它?

由于此项目结构(与 aks 基础设施一起)是根据模板构建的,因此我想要一个可以添加到此类模板中或者可以单独添加到代码中的解决方案。

gunicorn
  • 1 个回答
  • 14 Views
Martin Hope
Ixion Chowdhury
Asked: 2022-02-17 05:12:26 +0800 CST

在具有不同子域(NGINX、Gunicorn、ubuntu)的同一个 Droplet 中托管两个不同的 django 项目

  • 0

正如标题所说,我想在具有不同子域的同一个 Droplet(NGINX、Gunicorn、ubuntu)中托管两个不同的 django 项目。其中一个是我们的主站点 example.com。它已启动并运行并完美运行。我们希望在同一个 Droplet 中托管临时站点 staging.example.com。

我们已经为暂存站点创建了新的套接字和服务文件并激活并启用了它们,但问题是 nginx 仍然指向主域目录中的文件而不是暂存目录,因此即使已添加这些域,我们也会在下面收到此错误在暂存站点的 settings.py 允许的主机中

DisallowedHost at / 无效的 HTTP_HOST 标头:“staging.example.com”。您可能需要将 >'staging.example.com' 添加到 ALLOWED_HOSTS

这是我们的 staging.guinicorn.service 文件

[Unit]
Description=staging.gunicorn daemon
Requires=staging.gunicorn.socket
After=network.target

[Service]
User=admin
Group=www-data
WorkingDirectory=/home/admin/example1staging
ExecStart=/home/admin/example1staging/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/staging.gunicorn.sock djangoproject.wsgi:application

[Install]
WantedBy=multi-user.target

这是我们的 staging.guicorn.socket 文件

[Unit]
Description=staging.gunicorn socket

[Socket]
ListenStream=/run/staging.gunicorn.sock

[Install]
WantedBy=sockets.target

最后是我们的 nginx 配置

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    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;
    ssl_client_certificate /etc/ssl/cloudflare.crt;
    ssl_verify_client on;

    root /var/www/html;
    index index.html index.htm index.nginx-debian.html;    

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/admin/example1;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}

server {
    listen 80;
    listen [::]:80;
    server_name staging.example.com www.staging.example.com;
    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;
    ssl_client_certificate /etc/ssl/cloudflare.crt;
    ssl_verify_client on;

    root /var/www/html;
    index index.html index.htm index.nginx-debian.html;    

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/admin/example1staging;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/staging.gunicorn.sock;
    }
}

任何形式的帮助将不胜感激!

ubuntu django nginx ubuntu-20.04 gunicorn
  • 2 个回答
  • 149 Views
Martin Hope
Lunartist
Asked: 2022-01-28 18:05:23 +0800 CST

Nginx 重定向到 http://localhost

  • 0

情况简图

  • 我无法使用域地址,server_name因为我无法控制 DNS 服务器。我必须使用公共 IP 连接到我的 Web 服务器。
  • 所以我设置server_name为_;,但是当我请求http://firewall-public-ip:5000它重定向到http://localhost:5000.
  • 我通常可以打开其他不使用重定向的页面。例如,我可以访问http://firewall-public-ip:5000/login并登录,但它会重定向到,http://localhost:5000/login因为登录页面在登录后使用重定向。

nginx.conf:

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 4096;
    proxy_hide_header X-Powered-By;
    proxy_hide_header Server;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

server {
    listen 5000;

    server_name _;
    server_name_in_redirect off;
    ssl_protocols TLSv1.2;

    location '/' {
        proxy_pass http://unix:/var/sockets/gunicorn.sock;
    }
  }
}

我该如何解决?同样,我不能使用此服务器的域地址。

*EDIT 添加了应用程序重定向

@blueprint.route('/')
def route_default():
    return redirect(url_for('authentication_blueprint.login'))


@blueprint.route('/login', methods=['GET', 'POST'])
def login():
    login_form = LoginForm(request.form)
    if 'login' in request.form:

        # read form data
        username = request.form['username']
        password = request.form['password']

        # Locate user
        user = Users.query.filter_by(username=username).first()

        # Check the password
        if user and verify_pass(password, user.password):

            login_user(user)
            return redirect(url_for('authentication_blueprint.route_default'))

        # Something (user or pass) is not ok
        return render_template('accounts/login.html',
                               msg='Wrong user or password',
                               form=login_form)

    if not current_user.is_authenticated:
        return render_template('accounts/login.html',
                               form=login_form)
    return redirect(url_for('home_blueprint.index'))

apps.authentication.__init__.py

from flask import Blueprint

blueprint = Blueprint(
    'authentication_blueprint',
    __name__,
    url_prefix=''
)
redirect nginx gunicorn proxypass
  • 1 个回答
  • 434 Views
Martin Hope
Gaetan GR
Asked: 2021-12-29 10:38:06 +0800 CST

主管没有使用 Django 项目正确重新加载 Gunicorn

  • 1

在将Django项目推向生产时,我正在使用Supervisor重新加载Gunicorn :

工作流程:

          " && python manage.py migrate"\
          " && python manage.py collectstatic --noinput"\
          " && supervisorctl restart frontdesk-gunicorn"\
          " && exit"

主管配置:

   [program:project-gunicorn]
    command=/home/gaetangr/project/myprojectenv/bin/gunicorn config.wsgi:application
    user = gaetangr
    directory = /home/gaetangr/project
    autostart = true
    autorestart = true

但大多数时候,为了传播所有的变化,我必须做一个 sudo :

systemctl restart gunicorn

据我了解,主管的命令应该完全相同。

任何想法 ?

linux ubuntu django gunicorn supervisord
  • 1 个回答
  • 292 Views
Martin Hope
Zev
Asked: 2021-10-14 09:52:13 +0800 CST

由 psycopg2.OperationalError 引起的间歇性 500 错误:无法翻译主机名

  • 0

对我们的后端 Django 应用程序(使用 ECS 和 Postgres RDS 部署在 AWS 上)的请求中有 20% 会引发 500 错误。查看 ECS 日志,显示了各种相关错误:

psycopg2.OperationalError: could not translate host name "abc.efg.us-east-1.rds.amazonaws.com" to address
OSError: [Errno 16] Device or resource busy
<built-in function getaddrinfo>) failed with OSError

我们使用 gunicorn 和 gevent 来服务我们的应用程序:

gunicorn -t 1000 -k gevent -w 4 -b 0.0.0.0:8000 backend.wsgi

domain-name-system amazon-ecs gunicorn amazon-rds
  • 1 个回答
  • 864 Views
Martin Hope
Madhav
Asked: 2021-09-29 20:21:23 +0800 CST

Urls.py 未在使用 nginx 和 gunicorn 的 Django 生产服务器上更新

  • 2

我目前在 AWS EC2 实例上托管 Django Webapp,为了在生产模式下运行它,我使用 NGINX 和 gunicorn。

我面临的错误是:

无论我做什么,生产服务器似乎都不会更新 urls.py

用于将文件从本地文件传输到实例的应用程序:FileZilla

我为解决该问题而采取的步骤:

  1. 删除 urls.py 并重写它

  2. 检查其他文件是否也拒绝更新

    第二步的结果:其他文件已成功更新,我使用静态文件和 index.html 进行了测试

  3. 使用纳米编辑器检查文件是否在实例中更新

    第 3 步的结果:文件在实例中正确更新,所有更改都被反映

  4. 使用(用于开发目的)在实例上运行它python manage.py runserver,并发现使用 runserver 时 urls.py 正在正确更新

其他信息:

1.昨天一切都在正常更新,但突然决定叛逆

  1. 我已经使用更新了所有软件包sudo yum install

  2. 我已经重新启动了 nginx 和 gunicorn:使用以下命令:

    sudo systemctl start gunicorn

    sudo systemctl enable gunicorn

    sudo systemctl restart nginx

  3. 我尝试使用检查错误sudo nginx -t,但没有出现错误

  4. 我已经检查了错误日志,使用sudo tail -f /var/log/nginx/error.log,但
    这里也没有显示错误

我该如何解决这个问题?

谢谢

django amazon-ec2 nginx gunicorn
  • 1 个回答
  • 370 Views
Martin Hope
Paul
Asked: 2021-08-07 04:47:32 +0800 CST

如何使用 Supervisor(包括 Gunicorn 和 Nginx)设置多个 Django 应用程序?bind() to [::]:8090 失败(98:地址已在使用中)

  • 1

我已经使用 Supervisor、Gunicorn 和 Nginx(在 Debian Buster 上)部署了一个 Django/Wagtail 应用程序,所以我可以通过http://xx.xxx.xxx.xxx:8090访问它。

/etc/nginx/sites-available/cms

server {
    server_name xx.xxx.xxx.xxx;
    listen 8090;
    listen [::]:8090 ipv6only=on;
    error_log /home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/gunicorn-error.log;
    access_log /home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/gunicorn-access.log;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/www.mysite.com/www/my-site/cms/admin_panel;
    }
        location /media/ {
        root /home/www.mysite.com/www/my-site/cms/admin_panel;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/run/gunicorn.sock;
    }
}
/etc/supervisor/conf.d/guni-mysite-admin.conf

[program:guni-mysite-admin]
command=/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/bin/gunicorn admin_panel.wsgi:application --config /home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/etc/gunicorn/conf.py
user=www.mysite.com
autostart=true
autorestart=true
/etc/supervisor/conf.d/nginx-mysite-admin.conf

[program:nginx-mysite-admin]
command=/usr/sbin/nginx -g "daemon off;"
autostart=true
autorestart=true
stderr_logfile=/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/nginx-error.log
stdout_logfile=/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/nginx-access.log
stderr_logfile_maxbytes=2MB
stdout_logfile_maxbytes=2MB
/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/etc/gunicorn/conf.py

workers = 3
keepalive = 5
user = 'www.mysite.com'
proc_name = 'admin_panel'
loglevel = 'error'
errorlog = '/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/gunicorn-error.log'
accesslog = '/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/gunicorn-access.log'
bind = 'unix:/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/run/gunicorn.sock'
raw_env = ['DJANGO_SETTINGS_MODULE=admin_panel.settings.production']
pythonpath = '/home/www.mysite.com/www/mysite/cms/admin_panel'

现在我以同样的方式添加了另外 2 个 Django 应用程序。不幸的是,主管无法提出他们。有时 3 次运行中有 1 次运行,但大多数时候它们都不起作用。如果它有效,它会创建 3 个进程(idk,如果它应该是这样的话)。

$ sudo lsof -i:8090

COMMAND  PID     USER   FD   TYPE    DEVICE SIZE/OFF NODE NAME
nginx   3631     root   16u  IPv4 961301189      0t0  TCP *:8090 (LISTEN)
nginx   3631     root   17u  IPv6 961301190      0t0  TCP *:8090 (LISTEN)
nginx   3632 www-data   16u  IPv4 961301189      0t0  TCP *:8090 (LISTEN)
nginx   3632 www-data   17u  IPv6 961301190      0t0  TCP *:8090 (LISTEN)
nginx   3633 www-data   16u  IPv4 961301189      0t0  TCP *:8090 (LISTEN)
nginx   3633 www-data   17u  IPv6 961301190      0t0  TCP *:8090 (LISTEN)

Nginx 错误日志给出98: Address already in use,即使在端口 81 上(将其作为默认端口,因为 Apache 正在使用 80),未使用。Apache 应该不是问题,因为它不起作用,即使 Apache 已关闭。

/var/log/nginx/error.log

...
2021/08/06 12:41:54 [emerg] 24927#24927: bind() to [::]:4020 failed (98: Address already in use)
2021/08/06 12:41:54 [emerg] 24927#24927: bind() to [::]:8090 failed (98: Address already in use)
2021/08/06 12:41:54 [emerg] 24927#24927: bind() to [::]:81 failed (98: Address already in use)
2021/08/06 12:41:54 [emerg] 24927#24927: bind() to [::]:8070 failed (98: Address already in use)
2021/08/06 12:41:54 [emerg] 24927#24927: bind() to [::]:8080 failed (98: Address already in use)
2021/08/06 12:41:54 [emerg] 24927#24927: bind() to [::]:4030 failed (98: Address already in use)
2021/08/06 12:41:54 [emerg] 24928#24928: still could not bind()
...

输出 - # nginx -T

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
# configuration file /etc/nginx/nginx.conf:
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}


#mail {
#   # See sample authentication script at:
#   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
#
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }
#}

# configuration file /etc/nginx/modules-enabled/50-mod-http-auth-pam.conf:
load_module modules/ngx_http_auth_pam_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-dav-ext.conf:
load_module modules/ngx_http_dav_ext_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-echo.conf:
load_module modules/ngx_http_echo_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-geoip.conf:
load_module modules/ngx_http_geoip_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-image-filter.conf:
load_module modules/ngx_http_image_filter_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-subs-filter.conf:
load_module modules/ngx_http_subs_filter_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-upstream-fair.conf:
load_module modules/ngx_http_upstream_fair_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-xslt-filter.conf:
load_module modules/ngx_http_xslt_filter_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-mail.conf:
load_module modules/ngx_mail_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-stream.conf:
load_module modules/ngx_stream_module.so;

# configuration file /etc/nginx/mime.types:

types {
    text/html                             html htm shtml;
    text/css                              css;
    text/xml                              xml;
    image/gif                             gif;
    image/jpeg                            jpeg jpg;
    application/javascript                js;
    application/atom+xml                  atom;
    application/rss+xml                   rss;

    text/mathml                           mml;
    text/plain                            txt;
    text/vnd.sun.j2me.app-descriptor      jad;
    text/vnd.wap.wml                      wml;
    text/x-component                      htc;

    image/png                             png;
    image/tiff                            tif tiff;
    image/vnd.wap.wbmp                    wbmp;
    image/x-icon                          ico;
    image/x-jng                           jng;
    image/x-ms-bmp                        bmp;
    image/svg+xml                         svg svgz;
    image/webp                            webp;

    application/font-woff                 woff;
    application/java-archive              jar war ear;
    application/json                      json;
    application/mac-binhex40              hqx;
    application/msword                    doc;
    application/pdf                       pdf;
    application/postscript                ps eps ai;
    application/rtf                       rtf;
    application/vnd.apple.mpegurl         m3u8;
    application/vnd.ms-excel              xls;
    application/vnd.ms-fontobject         eot;
    application/vnd.ms-powerpoint         ppt;
    application/vnd.wap.wmlc              wmlc;
    application/vnd.google-earth.kml+xml  kml;
    application/vnd.google-earth.kmz      kmz;
    application/x-7z-compressed           7z;
    application/x-cocoa                   cco;
    application/x-java-archive-diff       jardiff;
    application/x-java-jnlp-file          jnlp;
    application/x-makeself                run;
    application/x-perl                    pl pm;
    application/x-pilot                   prc pdb;
    application/x-rar-compressed          rar;
    application/x-redhat-package-manager  rpm;
    application/x-sea                     sea;
    application/x-shockwave-flash         swf;
    application/x-stuffit                 sit;
    application/x-tcl                     tcl tk;
    application/x-x509-ca-cert            der pem crt;
    application/x-xpinstall               xpi;
    application/xhtml+xml                 xhtml;
    application/xspf+xml                  xspf;
    application/zip                       zip;

    application/octet-stream              bin exe dll;
    application/octet-stream              deb;
    application/octet-stream              dmg;
    application/octet-stream              iso img;
    application/octet-stream              msi msp msm;

    application/vnd.openxmlformats-officedocument.wordprocessingml.document    docx;
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet          xlsx;
    application/vnd.openxmlformats-officedocument.presentationml.presentation  pptx;

    audio/midi                            mid midi kar;
    audio/mpeg                            mp3;
    audio/ogg                             ogg;
    audio/x-m4a                           m4a;
    audio/x-realaudio                     ra;

    video/3gpp                            3gpp 3gp;
    video/mp2t                            ts;
    video/mp4                             mp4;
    video/mpeg                            mpeg mpg;
    video/quicktime                       mov;
    video/webm                            webm;
    video/x-flv                           flv;
    video/x-m4v                           m4v;
    video/x-mng                           mng;
    video/x-ms-asf                        asx asf;
    video/x-ms-wmv                        wmv;
    video/x-msvideo                       avi;
}

# configuration file /etc/nginx/conf.d/timeout.conf:
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;

# configuration file /etc/nginx/sites-enabled/admin.mysite_2:
server {
    server_name xx.xxx.xxx.xxx;
    listen 4020;
    listen [::]:4020 ipv6only=on;
    error_log /home/www.mysite_2/.local/share/virtualenvs/cms-CiomF2CE/var/log/gunicorn-error.log;
    access_log /home/www.mysite_2/.local/share/virtualenvs/cms-CiomF2CE/var/log/gunicorn-access.log;

    # add_header 'Access-Control-Allow-Origin' '*';
    # add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    # add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/mysite_2/www/translator-app-python/cms/wagtail_cms;
    }
        location /media/ {
        root /home/mysite_2/www/translator-app-python/cms/wagtail_cms;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/mysite_2/.local/share/virtualenvs/cms-CiomF2CE/run/gunicorn.sock;
    }
}
# configuration file /etc/nginx/proxy_params:
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

# configuration file /etc/nginx/sites-enabled/cms:
server {
    server_name xx.xxx.xxx.xxx;
    listen 8090;
    listen [::]:8090 ipv6only=on;
    error_log /home/mysite_1/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/gunicorn-error.log;
    access_log /home/mysite_1/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/gunicorn-access.log;

    # add_header 'Access-Control-Allow-Origin' '*';
    # add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    # add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/mysite_1/www/kc-site/cms/admin_panel;
    }
        location /media/ {
        root /home/wmysite_1/www/kc-site/cms/admin_panel;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/mysite_1/.local/share/virtualenvs/cms-WqsZ9qOt/run/gunicorn.sock;
    }
}
# configuration file /etc/nginx/sites-enabled/default:
##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# https://www.nginx.com/resources/wiki/start/
# https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/
# https://wiki.debian.org/Nginx/DirectoryStructure
#
# In most cases, administrators will remove this file from sites-enabled/ and
# leave it as reference inside of sites-available where it will continue to be
# updated by the nginx packaging team.
#
# This file will automatically load configuration files provided by other
# applications, such as Drupal or Wordpress. These applications will be made
# available underneath a path with that package name, such as /drupal8.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
server {
    # alte Syntax
    listen 81 default_server;
    listen [::]:81 ipv6only=on default_server;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    #
    # Read up on ssl_ciphers to ensure a secure configuration.
    # See: https://bugs.debian.org/765782
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;

    root /var/www/html/Nginx;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html index.php ;

    server_name _;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
    }

    # pass PHP scripts to FastCGI server ( neu )
    #
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        include /etc/nginx/conf.d/*.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }

    # pass PHP scripts to FastCGI server
    #
    #location ~ \.php$ {
    #   include snippets/fastcgi-php.conf;
    #
    #   # With php-fpm (or other unix sockets):
    #   fastcgi_pass unix:/run/php/php7.3-fpm.sock;
    #   # With php-cgi (or other tcp sockets):
    #   # fastcgi_pass 127.0.0.1:9000;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #   deny all;
    #}
}


# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#   listen 80;
#   listen [::]:80;
#
#   server_name example.com;
#
#   root /var/www/example.com;
#   index index.html;
#
#   location / {
#       try_files $uri $uri/ =404;
#   }
#}

# configuration file /etc/nginx/snippets/fastcgi-php.conf:
# regex to split $uri to $fastcgi_script_name and $fastcgi_path
fastcgi_split_path_info ^(.+?\.php)(/.*)$;

# Check that the PHP script exists before passing it
try_files $fastcgi_script_name =404;

# Bypass the fact that try_files resets $fastcgi_path_info
# see: http://trac.nginx.org/nginx/ticket/321
set $path_info $fastcgi_path_info;
fastcgi_param PATH_INFO $path_info;

fastcgi_index index.php;
include fastcgi.conf;

# configuration file /etc/nginx/fastcgi.conf:

fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  REQUEST_SCHEME     $scheme;
fastcgi_param  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

# configuration file /etc/nginx/sites-enabled/kcanalytics:
server {
    server_name xx.xxx.xxx.xxx;
    listen 8070;
    listen [::]:8070 ipv6only=on;
    root /home/mysite_1/www/kc-site/Open-Web-Analytics;
    index index.php index.html index.htm;
    location / {
        try_files $uri $uri/ =404;
    }
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        include /etc/nginx/conf.d/*.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }
    error_log /var/log/nginx/kcanalyticslog/kcanalytics-error.log;
    access_log /var/log/nginx/kcanalyticslog/kcanalytics-access.log;
}

# configuration file /etc/nginx/sites-enabled/kcclient:
server {
    server_name xx.xxx.xxx.xxx;
    listen 8080;
    listen [::]:8080 ipv6only=on;
    root /var/www/html/Nginx;
    index index.nginx-debian.html;

    location / {
    proxy_pass http://localhost:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
    }
}

# configuration file /etc/nginx/sites-enabled/phrases-api.mysite_2:
server {
    server_name xx.xxx.xxx.xxx;
    listen 4030;
    listen [::]:4030 ipv6only=on;
    error_log /home/mysite_2/.local/share/virtualenvs/api-dAF0CRIW/var/log/gunicorn-error.log;
    access_log /home/mysite_2/.local/share/virtualenvs/api-dAF0CRIW/var/log/gunicorn-access.log;

    # add_header 'Access-Control-Allow-Origin' '*';
    # add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    # add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/mysite_2/www/translator-app-python/api/translator_rest_api;
    }
        location /media/ {
        root /home/mysite_2/www/translator-app-python/api/translator_rest_api;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/mysite_2/.local/share/virtualenvs/api-dAF0CRIW/run/gunicorn.sock;
    }
}
linux django nginx gunicorn supervisord
  • 1 个回答
  • 225 Views
Martin Hope
bolino
Asked: 2021-07-10 02:17:08 +0800 CST

调试 Nginx 虚拟主机作为 Uvicorn Python API 的反向代理

  • 0

我有一个(Python,基于 DRF)API,作为 Uvicorn 服务在 Debian 服务器的 8002 端口上运行。它运行时没有明显问题,因为当我这样做时curl http://127.0.0.1:8002/videos/,我得到了预期的 API 响应(我在 Heroku 上部署时也对其进行了测试,没有问题)。

我需要使用 Nginx 公开提供它,所以我配置了一个新的 Nginx vhost 作为反向代理,如下所示:

 upstream my_api {
     server 127.0.0.1:8002;
 }
 
 server {
 
     server_name example.com;
 
     location / {
         # Pass to Uvicorn/Gunicorn web server service
         proxy_pass http://my_api;
         proxy_set_header Host $host;
         proxy_set_header X-Real-IP $remote_addr;
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
         proxy_set_header X-Forwarded-Proto $scheme;
     }

}

error_log /home/www/mydomain.log info;

在浏览器上,我收到 400 Bad Request 错误,无论是 onhttp://example.com/videos/还是 on http://example.com/or http://example.com/whatever。

当我/home/www/example.log跟踪 Nginx 虚拟主机日志文件时,我没有得到任何相关信息或来自其他虚拟主机的日志,如下所示:

2021/07/09 12:05:49 [info] 24698#24698: *233765 client 55.36.148.206 closed keepalive connection
2021/07/09 12:06:12 [info] 24698#24698: *233772 client 217.244.66.202 closed keepalive connection
2021/07/09 12:06:13 [info] 24698#24698: *233775 client closed connection while waiting for request, client: 63.210.40.102, server: 0.0.0.0:80

(注意:唯一端点适用于/videos/路由,但不适用于/videos路由 - 这将在稍后修复,但无论如何不应干扰问题。)

知道如何调试/理解这个 400 错误的来源吗?

nginx gunicorn
  • 1 个回答
  • 555 Views
Martin Hope
G M
Asked: 2021-04-02 08:46:57 +0800 CST

使用 gunicorn 和 Nginx 服务多个套接字会导致 NotFound 错误

  • 0

我正在尝试使用 Nginx 作为反向代理来提供两个 Flask 应用程序。在我default.conf 重新加载的sudo service nginx restart我有:

    location /app2loc/ {
            include proxy_params;
            proxy_pass http://unix:/var/www/html/app2/app.sock;
    }
    location / {
            include proxy_params;
            proxy_pass http://unix:/var/www/html/app1/app.sock;
    }

当app1我在www.mydomain.com. 第二个应用程序app2似乎运行有任何错误作为证据,这是输出sudo systemctl status app2.service:

● app2.service - Gunicorn instance to serve Flask app2.
   Loaded: loaded (/etc/systemd/system/capitcatalog.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2021-04-01 18:11:28 CEST; 26min ago
 Main PID: 24762 (gunicorn)
    Tasks: 25 (limit: 4423)
   CGroup: /system.slice/capitcatalog.service
           ├─24762 /var/www/html/app2/env/bin/python3.6 /var/www/html/app2/env/bin/gunicorn --chdir /var/www/html/app2/ -w 3 -b unix:app.sock -m 007 
           ├─24778 /var/www/html/app2/env/bin/python3.6 /var/www/html/app2/env/bin/gunicorn --chdir /var/www/html/app2/ -w 3 -b unix:app.sock -m 007 
           ├─24779 /var/www/html/app2/env/bin/python3.6 /var/www/html/app2/env/bin/gunicorn --chdir /var/www/html/app2/ -w 3 -b unix:app.sock -m 007 
           └─24780 /var/www/html/app2/env/bin/python3.6 /var/www/html/app2/env/bin/gunicorn --chdir /var/www/html/app2/ -w 3 -b unix:app.sock -m 007

但是,当我尝试使用它访问它时,www.mydomain.com/app2loc我有一个

Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

我想知道可能是什么错误。为什么第二个套接字似乎无法访问?

这是的输出nginx -T:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
# configuration file /etc/nginx/nginx.conf:
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    #include /etc/nginx/sites-enabled/*;

    # ADDED FOR UV VIEWR
    proxy_cache_key $scheme$proxy_host$uri;
    fastcgi_cache_key "$scheme$host$uri";


}


#mail {
#   # See sample authentication script at:
#   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
# 
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
# 
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
# 
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }
#}

# configuration file /etc/nginx/modules-enabled/50-mod-http-geoip.conf:
load_module modules/ngx_http_geoip_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-image-filter.conf:
load_module modules/ngx_http_image_filter_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-xslt-filter.conf:
load_module modules/ngx_http_xslt_filter_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-mail.conf:
load_module modules/ngx_mail_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-stream.conf:
load_module modules/ngx_stream_module.so;

# configuration file /etc/nginx/mime.types:

types {
    text/html                             html htm shtml;
    text/css                              css;
    text/xml                              xml;
    image/gif                             gif;
    image/jpeg                            jpeg jpg;
    application/javascript                js;
    application/atom+xml                  atom;
    application/rss+xml                   rss;

    text/mathml                           mml;
    text/plain                            txt;
    text/vnd.sun.j2me.app-descriptor      jad;
    text/vnd.wap.wml                      wml;
    text/x-component                      htc;

    image/png                             png;
    image/tiff                            tif tiff;
    image/vnd.wap.wbmp                    wbmp;
    image/x-icon                          ico;
    image/x-jng                           jng;
    image/x-ms-bmp                        bmp;
    image/svg+xml                         svg svgz;
    image/webp                            webp;

    application/font-woff                 woff;
    application/java-archive              jar war ear;
    application/json                      json;
    application/mac-binhex40              hqx;
    application/msword                    doc;
    application/pdf                       pdf;
    application/postscript                ps eps ai;
    application/rtf                       rtf;
    application/vnd.apple.mpegurl         m3u8;
    application/vnd.ms-excel              xls;
    application/vnd.ms-fontobject         eot;
    application/vnd.ms-powerpoint         ppt;
    application/vnd.wap.wmlc              wmlc;
    application/vnd.google-earth.kml+xml  kml;
    application/vnd.google-earth.kmz      kmz;
    application/x-7z-compressed           7z;
    application/x-cocoa                   cco;
    application/x-java-archive-diff       jardiff;
    application/x-java-jnlp-file          jnlp;
    application/x-makeself                run;
    application/x-perl                    pl pm;
    application/x-pilot                   prc pdb;
    application/x-rar-compressed          rar;
    application/x-redhat-package-manager  rpm;
    application/x-sea                     sea;
    application/x-shockwave-flash         swf;
    application/x-stuffit                 sit;
    application/x-tcl                     tcl tk;
    application/x-x509-ca-cert            der pem crt;
    application/x-xpinstall               xpi;
    application/xhtml+xml                 xhtml;
    application/xspf+xml                  xspf;
    application/zip                       zip;

    application/octet-stream              bin exe dll;
    application/octet-stream              deb;
    application/octet-stream              dmg;
    application/octet-stream              iso img;
    application/octet-stream              msi msp msm;

    application/vnd.openxmlformats-officedocument.wordprocessingml.document    docx;
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet          xlsx;
    application/vnd.openxmlformats-officedocument.presentationml.presentation  pptx;

    audio/midi                            mid midi kar;
    audio/mpeg                            mp3;
    audio/ogg                             ogg;
    audio/x-m4a                           m4a;
    audio/x-realaudio                     ra;

    video/3gpp                            3gpp 3gp;
    video/mp2t                            ts;
    video/mp4                             mp4;
    video/mpeg                            mpeg mpg;
    video/quicktime                       mov;
    video/webm                            webm;
    video/x-flv                           flv;
    video/x-m4v                           m4v;
    video/x-mng                           mng;
    video/x-ms-asf                        asx asf;
    video/x-ms-wmv                        wmv;
    video/x-msvideo                       avi;
}

# configuration file /etc/nginx/conf.d/default.conf:

server {
        server_name www.mydomain.com;
        listen 80;
        root /var/www/html/;

    # this is working properly 
    location /vrt/ {
            alias /var/www/html/vrt/; 
        }

    location /app2/ {
                include proxy_params;
                proxy_pass http://unix:/var/www/html/app2/app.sock;
        }

}        

# configuration file /etc/nginx/proxy_params:
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
nginx socket gunicorn flask
  • 1 个回答
  • 205 Views
Martin Hope
Fernando Tholl
Asked: 2021-03-17 13:54:07 +0800 CST

使用 Python、Apache(代理)和 SSL 的静态文件 [重复]

  • 0
这个问题在这里已经有了答案:
如何向 apache 反向代理规则添加例外 [重复] 1 个回答
去年关闭。

这是我在社区的第一个问题,如果我写错了,我提前道歉

我在 Python (Django) 中开发了一个应用程序,并且在质量环境中我使用 gunicorn 来提供部署:gunicorn --bind 0.0.0.0:8000 application.wsgi --daemon

在同一台服务器上,我使用 Apache 监听端口 443 (https://) 并通过代理将请求重定向到 Gunicorn,如下所示:

  <VirtualHost *:443>
  
        ServerName example.com   

        ProxyRequests Off
        ProxyPreserveHost On
        
        <Proxy *>
                Require all granted
                Allow from all
        </Proxy>

        ProxyPass / http://example.com:8000/
        ProxyPassReverse / http://example.com:8000/

        # SSL
        SSLEngine On

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

        #Include conf-available
        SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
        Include /etc/letsencrypt/options-ssl-apache.conf

</VirtualHost>

一切正常,我可以通过 https 访问它,除了静态文件。

我按照文档的建议,执行了命令collectstatic,文件是在我在 settings.py 中配置的文件夹(/static)中生成的

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/') 

我利用了我已经安装了 Apache 的优势,我尝试在同一个 VirtualHost 中添加 /static 目录的别名,如下所示:

Alias /static "/home/ubuntu/example/static/"
<Directory "/home/ubuntu/example/static">
      Order allow,deny  
      Allow from all
      Require all granted
</Directory>

VirtualHost 的完整配置如下所示:

 <VirtualHost *:443>
  
        ServerName example.com  

        Alias /static "/home/ubuntu/example/static/"
        <Directory "/home/ubuntu/example/static">
              Order allow,deny  
              Allow from all
              Require all granted
        </Directory>

        ProxyRequests Off
        ProxyPreserveHost On
        
        <Proxy *>
                Require all granted
                Allow from all
        </Proxy>

        ProxyPass / http://example.com:8000/
        ProxyPassReverse / http://example.com:8000/

        # SSL
        SSLEngine On

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

        #Include conf-available
        SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
        Include /etc/letsencrypt/options-ssl-apache.conf

</VirtualHost>

但是,当尝试访问此目录中的文件时,我总是得到一个:

未找到 - 在此服务器上未找到请求的资源。

我分析了 error.log 和 access.log,甚至没有在日志中点击请求。

将相同的别名添加到端口 80 上的另一个虚拟主机,它可以正常工作。我认为问题在于将此别名添加到端口 443 的特定 VirtualHost

你能帮助我吗?

django python apache2 gunicorn
  • 1 个回答
  • 700 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    新安装后 postgres 的默认超级用户用户名/密码是什么?

    • 5 个回答
  • Marko Smith

    SFTP 使用什么端口?

    • 6 个回答
  • Marko Smith

    命令行列出 Windows Active Directory 组中的用户?

    • 9 个回答
  • Marko Smith

    什么是 Pem 文件,它与其他 OpenSSL 生成的密钥文件格式有何不同?

    • 3 个回答
  • Marko Smith

    如何确定bash变量是否为空?

    • 15 个回答
  • Martin Hope
    Tom Feiner 如何按大小对 du -h 输出进行排序 2009-02-26 05:42:42 +0800 CST
  • Martin Hope
    Noah Goodrich 什么是 Pem 文件,它与其他 OpenSSL 生成的密钥文件格式有何不同? 2009-05-19 18:24:42 +0800 CST
  • Martin Hope
    Brent 如何确定bash变量是否为空? 2009-05-13 09:54:48 +0800 CST
  • Martin Hope
    cletus 您如何找到在 Windows 中打开文件的进程? 2009-05-01 16:47:16 +0800 CST

热门标签

linux nginx windows networking ubuntu domain-name-system amazon-web-services active-directory apache-2.4 ssh

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve