首页 > 解决方案 > 如何为隐藏链接创建永久重定向脚本

问题描述

我目前正在使用Yoast 隐藏脚本为附属链接创建临时重定向 (302)。例如,如果我导航到https://website.com/go/Site2,它会重定向到“https://redirectwebsite2.com”。

如何为永久重定向 (301) 调整以下内容?我尝试将标题从 302 更改为 301,但这不起作用。

以下文件保存在“public_html”WordPress 目录的“go”文件夹中。

.htaccess

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^index\.php$ - [L]
RewriteRule (.*) ./index.php?id=$1 [L]
</IfModule>

索引.php

<?php
 
$id     = isset( $_GET['id'] ) ? rtrim( trim( $_GET['id'] ), '/' ) : 'default';
$f  = fopen( 'redirects.txt', 'r' );
$urls   = array();
 
// The file didn't open correctly.
if ( !$f ) {
    echo 'Make sure you create your redirects.txt file and that it\'s readable by the redirect script.';
    die;
}
 
// Read the input file and parse it into an array
while( $data = fgetcsv( $f ) ) {
    if ( !isset( $data[0] ) || !isset( $data[1] ) )
        continue;
    
    $key = trim( $data[0] );
    $val = trim( $data[1] );
    $urls[ $key ] = $val;
}
 
// Check if the given ID is set, if it is, set the URL to that, if not, default
$url = ( isset( $urls[ $id ] ) ) ? $urls[ $id ] : ( isset( $urls[ 'default' ] ) ? $urls[ 'default' ] : false );

if ( $url ) {
    header( "X-Robots-Tag: noindex, nofollow", true );
    header( "Location: " .  $url, 302 );
    die;    
} else {
    echo '<p>Make sure yor redirects.txt file contains a default value, syntax:</p>
    <pre>default,http://example.com</pre>
    <p>Where you should replace example.com with your domain.</p>';
}

重定向.txt

default,https://website.com
Site1,https://redirectwebsite1.com
Site2,https://redirectwebsite2.com

标签: phpwordpress.htaccessredirect

解决方案


解决方案是将标头更改为 ( "X-Robots-Tag: noindex, nofollow", true, 301 )


<?php
 
$id     = isset( $_GET['id'] ) ? rtrim( trim( $_GET['id'] ), '/' ) : 'default';
$f  = fopen( 'redirects.txt', 'r' );
$urls   = array();
 
// The file didn't open correctly.
if ( !$f ) {
    echo 'Make sure you create your redirects.txt file and that it\'s readable by the redirect script.';
    die;
}
 
// Read the input file and parse it into an array
while( $data = fgetcsv( $f ) ) {
    if ( !isset( $data[0] ) || !isset( $data[1] ) )
        continue;
    
    $key = trim( $data[0] );
    $val = trim( $data[1] );
    $urls[ $key ] = $val;
}
 
// Check if the given ID is set, if it is, set the URL to that, if not, default
$url = ( isset( $urls[ $id ] ) ) ? $urls[ $id ] : ( isset( $urls[ 'default' ] ) ? $urls[ 'default' ] : false );

if ( $url ) {
    header( "X-Robots-Tag: noindex, nofollow", true, 301 );
    header( "Location: " .  $url );
    die;    
} else {
    echo '<p>Make sure yor redirects.txt file contains a default value, syntax:</p>
    <pre>default,http://example.com</pre>
    <p>Where you should replace example.com with your domain.</p>';
}


推荐阅读