smirnov-tk/redirect-bundle

处理重定向的Symfony扩展包

安装: 20

依赖: 0

建议者: 0

安全: 0

星标: 1

关注者: 0

分支: 3

类型:symfony-bundle

0.3.3 2022-04-30 18:46 UTC

README

Build Status Maintainability Test Coverage

在迁移或对您的app/网站进行结构更改后配置重定向。

它捕获异常事件,如果它们是类型NotFoundHttpException,它将查找配置的规则,并返回一个RedirectResponse响应来重定向用户。

适用于Symfony ^4.2或^5.0,与PHP >= 7.1.3和< 8.2兼容

它被设计得尽可能不引人注目,因为进行此类操作的需求通常是临时的 - Google建议将其保留一年。只需包含此包并添加一个配置重定向规则的配置块。

安装

通过Composer安装

$ composer require smirnov-tk/redirect-bundle

bundles.php中包含该包

# config/bundles.php

return [
    // All your bundles
    
    Autologic\Bundle\RedirectBundle\AutologicRedirectBundle::class => ['all' => true],
];

配置

基本用法

# app/config/packages/autologic_redirect.yaml

autologic_redirect:
  rules:
    - { pattern: '/old-route/', redirect: 'domain.com/new-route' }

pattern (字符串,必需)

使用正则表达式匹配请求的完整URI。服务捕获404异常,在无法匹配时抛出404事件之前,使用preg_match查找与丢失页面URI匹配的规则。

redirect (字符串,必需)

完整的重定向URI。该包将根据传入的原始请求设置协议(http/https),因此它可以从开发环境轻松迁移到生产环境。

full_url (布尔值,可选)

指定是否在完整URL(包括协议、域名、路径和查询)上匹配模式,或者只匹配路径和查询(默认:false)

status (整数,可选)

设置重定向的状态码(默认:301)。提示:在调试时使用302,以避免将301永久重定向缓存到浏览器中。

forwarding (布尔值,可选)

将原始路由附加到重定向(默认:false)。在以下情况下很有用:其他服务/应用程序已实施自己的重定向逻辑或路由结构在不同的域名或路径上相同。

absolute (布尔值,可选)

强制绝对或相对重定向(默认:null/auto)。如果未设置,它将检测重定向中的主机名,如果重定向不包含主机名,则使用原始请求主机,如果包含主机名,则使用重定向本身。

protocol (字符串,可选)

强制重定向协议(默认:null/auto)。如果未设置,它将检测原始请求的协议并使用该协议。

其他示例

# app/config.yml

autologic_redirect:
  rules:
    # custom status code
    - { pattern: '/old-route/', redirect: 'domain.com/new-route', status: 302 }
    # forwarding: this will redirect to domain.com/new-route/old-route
    - { pattern: '/old-route/', redirect: 'domain.com/new-route', forwarding: true }
    # absolute: will force relative or absolute redirects
    # if false it will redirect to the route on the current host
    - { pattern: '/old-route/', redirect: '/new-route', absolute: false }
    # protocol: will force the protocol
    - { pattern: '/old-route/', redirect: '/new-route', protocol: 'ftp://' }
    # priority: this first rule will match first when a user visits /old-route/sub-route, the second acting as a fallback
    - { pattern: '/.*old-route\/sub-route', redirect: 'domain.com/new-route/sub-route' }
    - { pattern: '/.*old-route/', redirect: 'domain.com/new-route' }
    # match subdomains and more complex patterns and use parameters
    - { pattern: '/au\..+?\.[^\/]+.*blog\/old-australian-blog-post-on-any-domain-of-subdomain/',
        redirect: 'au.%base_domain%/news/new-australian-news-article',
        full_url: true
      }

日志记录

要启用未匹配的404错误的日志记录,只需在services.yml中将记录器注入到监听器服务中

# app/services.yml

services:
  autologic_redirect.event.redirect_listener:
    class: Autologic\Bundle\RedirectBundle\Event\RedirectListener
    arguments:
      - '@autologic_redirect.service.redirect_service'
      - '@logger'
    tags:
      - { name: kernel.event_listener, event: kernel.exception }

这将以notice级别进行日志记录,以帮助发现没有重定向规则的404。