【问题标题】:Redirect URLs with a trailing slash to URLs with no trailing slash via htaccess rule with [QSA,L]通过带有 [QSA,L] 的 htaccess 规则将带有斜杠的 URL 重定向到没有斜杠的 URL
【发布时间】:2016-07-15 18:31:38
【问题描述】:

最近我与 WordPress 断绝关系,并将我网站的所有内容迁移到我自己定制的 CMS。除了一件事,一切都很好。以前指向我网站博客文章的所有链接都有一个尾部斜杠。由于我当前的 URL 都没有尾部斜杠,因此以前的链接不再有效,我的 SEO 几乎不存在。我一直在尝试找到一个 htaccess 规则,它将所有尾部斜杠 URL 重定向到没有尾部斜杠的 URL,但到目前为止,没有任何效果。

【问题讨论】:

  • 欢迎来到 Stack Overflow。我敢肯定,如果您发布到目前为止您所尝试的内容,人们会更愿意提供帮助。请参阅How to Ask a Good Question

标签: apache .htaccess redirect mod-rewrite trailing-slash


【解决方案1】:

使用此重定向规则作为删除尾部斜杠的第一条规则:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [NE,R=301,L]

【讨论】:

    【解决方案2】:

    您不想 100% 删除它以在 WordPress 中进行 SEO。#

    但是,如果您愿意,这将向您展示如何操作。 WordPress“/”修复。我的 WordPress Gist

    可以转换,所以很有帮助 配置文件:nginx.conf ...

    location  /mirror/foo/ {
            ...
            rewrite ^(.*[^/])$ $1/ permanent;
            ...
    }
    

    ...

    描述 WordPress "/" PHP 修复 如果博客设置为添加斜杠,则检索斜杠字符串。

    如果永久链接结构有尾部斜杠,则有条件地添加尾部斜杠,如果没有,则去除尾部斜杠。字符串通过‘user_trailingslashit’ 过滤器。如果博客未设置为包含斜杠,将从字符串中删除尾随斜杠。

    用法

    <?php user_trailingslashit( $string, $type_of_string ); ?>
    

    参数

    $string
    (string) (false) URL with or without a trailing slash.
    Default: None
    $type_of_url
    (string) (false) The type of URL being considered (e.g. single, category, etc) for use in the filter.
    Default: None
    Return Value (string) 
    

    根据永久链接结构添加/删除尾部斜杠。 codex.wordpress。 /Function_Reference/user_trailingslashit

    2。 如果要添加“/”

    <?php trailingslashit( $string ) ?>
    

    例子

    <?php
    $path = trailingslashit( '/home/julien/bin/dotfiles' ); 
    ?>
    

    $path 现在将包含:

    /home/julien/bin/dotfiles/
    

    (注意尾部的斜杠) https://codex.wordpress.org/Function_Reference/trailingslashit

    3。 这是新的 任何测试中最重要的部分是断言。断言是您期望从系统获得的值与您实际获得的值之间的比较。最简单的测试可能只包含一个断言。示例:

    public function test_trailingslashit_should_add_slash_when_none_is_present() {
        $this->assertSame( 'foo/', trailingslashit( 'foo' ) );
    }
    

    assertSame() 方法接受两个参数:期望值(在本例中为硬编码字符串 'foo/'),以及实际值(trailingslashit()) 返回的值。

    常见断言的注释列表可以在下面找到。 https://make.wordpress.org/core/handbook/testing/automated-testing/writing-phpunit-tests/#assertions

    试试这些规则:(in www.example.com's server block) rewrite ^/$ http://example.com permanent break; rewrite ^/main(.*)$ http://example.com$1 permanent break; rewrite ^(.*)$ http://blog.example.com$1 permanent; 确保你重新加载 nginx。
    使用此配置:

    1. http://www.example.com/ *重定向到
    2. http://example.comt -
    3. http://example.com/something - 其他所有内容都重定向到

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-01
      • 2014-12-22
      • 1970-01-01
      • 1970-01-01
      • 2018-12-21
      • 1970-01-01
      相关资源
      最近更新 更多