将短 URL 服务与 Nginx 上现有的 CMS 相结合

问题描述 投票:0回答:1

不久前,我创建了一个简单的内部短 URL 服务(使用 Django)。
如果存在某个条目,例如

/abc
(或其他),它会重定向到存储的较长 URL,HTTP 状态为 301。到目前为止,一切顺利...

但是,现在我需要为主网站设置此服务。

但是,已经有一个 CMS 运行并配置了 nginx

try_files
proxy_pass

Nginx:

location / {
    try_files /maintenance.html $uri @cms;
}

location @cms {
    rewrite ^/(.*)/$     /$1    permanent;
    rewrite              ^(.*)$ /VirtualHostBase/$scheme/$host:$server_port/cms/VirtualHostRoot$1 break;
    proxy_pass           http://example_cms;

    include              /etc/nginx/cfg/proxy.conf;
    include              /etc/nginx/cfg/security.conf;
    gzip_static          on; # to serve pre-gzipped version
}

这些可以组合吗? 因此,所需的流程如下:

  • 如果在短 URL 服务中找到并返回
    /abc
    ,则使用来自 URL 服务的 HTTP 状态进行重定向;
  • 否则,请使用 CMS 并使用
    try_files
    +
    rewrite
    +
    proxy_pass
    显示 CMS 中的 URL。
  • 如果这些都不适用,请显示 404,这也可以由 CMS 提供服务。
nginx nginx-reverse-proxy
1个回答
0
投票

您希望通过首先检查其路由来确定短 URL 服务的优先级,如果未找到匹配项,则继续像往常一样使用 CMS 处理请求。

               +-----> Django Short URL Service -----> 301 Redirect
              |
Request ----> |                                  
              |                                  
              +-----> CMS (via Nginx) -----------> Content/404

您需要通过添加新的

location
来修改 Nginx 配置,专门用于处理可能与您的短 URL 匹配的路径。 Django 应用程序必须设置为在特定端点或端口上提供服务,然后可由 Nginx 代理。

假设您的 Django 应用程序运行并侦听

localhost:8000
,您的 Nginx 配置将是:

http {
    # Other HTTP settings

    upstream django_short_url {
        server localhost:8000;
    }

    server {
        # Other server settings

        location / {
            try_files /maintenance.html $uri @short_url_service @cms;
        }

        location @short_url_service {
            proxy_pass http://django_short_url;
            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;
            # Additional proxy settings as needed

            # Handle only specific short URL patterns here if necessary,
            # Otherwise, this will pass all requests not found by try_files to Django.
        }

        location @cms {
            rewrite ^/(.*)/$     /$1    permanent;
            rewrite              ^(.*)$ /VirtualHostBase/$scheme/$host:$server_port/cms/VirtualHostRoot$1 break;
            proxy_pass           http://example_cms;

            include              /etc/nginx/cfg/proxy.conf;
            include              /etc/nginx/cfg/security.conf;
            gzip_static          on; # to serve pre-gzipped version
        }
    }
}

供您的 Django 应用程序使用的

upstream
,然后由
proxy_pass
引用:确保代理设置正确地将必要的标头转发到您的 Django 应用程序以正确处理请求。

@short_url_service
位置将处理 Django 应用程序的代理。
try_files
指令
已更新,以尝试直接提供文件,然后代理到 Django 应用程序,最后,如果两者都无法解决请求,则回退到 CMS 处理。


使用 NGINX 和 NGINX Plus 作为 uWSGI 和 Django 的应用程序网关”指南重点介绍了 Nginx 在通过 uWSGI 运行的 Django 应用程序前面充当应用程序网关的能力,这不是您的情况。

© www.soinside.com 2019 - 2024. All rights reserved.