.htaccess 重定向除主页htaccess之外的所有页面

sd2nnvve  于 2022-11-16  发布在  其他
关注(0)|答案(3)|浏览(155)

我有一个WordPress的网站,我试图重定向所有网页到同一个域的登陆页面,除了主页。我尝试了许多解决方案,发现互联网上,但没有一个工作。
我需要的是:

  • 主页和wp-admin页面应始终可访问(example.com和examplecom/wp-admin)
  • 所有其他页面应使用302代码重定向到example.com/redirect-page

先谢了

xa9qqrwz

xa9qqrwz1#

可能有更好的解决方案,但您可以尝试以下方法:
您可以使用$_SERVER['REQUEST_URI']来获取URL的一部分:
网址:www.example.com/abc/de
输出$_SERVER['REQUEST_URI']:/abc/de
然后可以使用<meta http-equiv="refresh" content="0; url=http://example.com/redirect-page" />进行重定向。
所以是这样的:

if($_SERVER['REQUEST_URI'] != "" && $_SERVER['REQUEST_URI'] != "/wp-admin") {
   echo '<meta http-equiv="refresh" content="0; url=http://example.com/" />';
}
ocebsuys

ocebsuys2#

您可以使用筛选器,该筛选器允许您创建一个例外,该例外具有基于当前配置处理网站重定向的代码。
https://plugins.trac.wordpress.org/browser/simple-website-redirect/trunk/SimpleWebsiteRedirect.php#L113
大概是这样的:

add_filter(
    'simple_website_redirect_should_redirect',
    function( $should_redirect, $url ) {

        if( home_url() === $url ) {
            return false;
        }

        return $should_redirect;   
    },
    10,
    2
);

HTTP访问:https://stackoverflow.com/a/38594600/19168006

编辑:您需要将该代码添加到您的主题functions.php

这是第二个解决方案:也许不如一个理论上的、功能上的.htaccess解决方案(如果存在的话)那么优雅。
//重定向除一个页面ID之外的整个站点

add_action( 'template_redirect', 'pc_redirect_site', 5 );
function pc_redirect_site(){
    
    $url = 'http://' . $_SERVER[ 'HTTP_HOST' ] . $_SERVER[ 'REQUEST_URI' ];
    $current_post_id = url_to_postid( $url );
    if ( ! is_admin() && ! is_page( 9999 )) { // Excludes page with this ID, and also the WordPress backend
        $id = get_the_ID();
        wp_redirect( 'http://example.com', 301 ); // You can change 301 to 302 if the redirect is temporary
        exit;
    } 
}

如果您不想重定向管理部分,请删除!is_admin() &&将http://example.com替换为您希望重定向通信的目标。默认情况下,这将执行301(永久)重定向;如果您希望这是临时的,请将301更改为302。显然,请用9999替换您希望排除的页面ID。

请注意,但是,如果您没有使用子主题,并且您打开了自动更新,则当您的主题强制更新时,它可能会在某个时候被覆盖,您必须再次更新它。

更多说明:here

2g32fytz

2g32fytz3#

在根.htaccess文件的顶部,# BEGIN WordPress注解标记 * 之前 * 尝试执行以下操作(您不需要重复RewriteEngine指令):

# Redirect all pages except "homepage", "wp-admin" and static assets
RewriteCond %{REQUEST_URI} !^/redirect-page$
RewriteCond %{REQUEST_URI} !^/wp-admin($|/)
RewriteCond %{REQUEST_URI} !\.\w{2,4}$
RewriteRule !^(index\.php)?$ /redirect-page [R=302,L]

我还在例外中包括了“静态资产”(图像、CSS、JS -任何带有文件扩展名的东西),因为我认为/redirect-page将需要访问这些资产。
当然,我们需要为/redirect-page本身设置一个例外,否则将导致无休止的重定向循环。
正则表达式 * 上的!前缀会否定 * 表达式,因此如果不匹配,则成功。
请注意,与REQUEST_URI服务器变量不同,RewriteRulepattern 匹配的URL路径不以斜杠开头。
如果您愿意,可以将上面的代码简化为一行代码(以可读性为代价):

RewriteRule !^(index\.php|redirect-page|wp-admin($|/.*)|.+\.\w{2,4})?$ /redirect-page [R=302,L]

相关问题