简体   繁体   English

htaccess 404错误条件代码为301重定向

[英]htaccess 404 error conditional code for 301 redirect

I have paginated URLs that look like http://www.domain.com/tag/apple/page/1/ 我的分页网址看起来像http://www.domain.com/tag/apple/page/1/

If a URL such as http://www.domain.com/tag/apple/page/*2/ doesn't exist, or page/2 doesn't exist, I need code to redirect this to a page such as http://www.domain.com/tag/apple/ which would be the main tag page. 如果不存在诸如http://www.domain.com/tag/apple/page/*2/的URL,或者page/2不存在,我需要代码将其重定向到诸如http://www.domain.com/tag/apple/的页面http://www.domain.com/tag/apple/这将是主要的标签页面。

I've currently have the following code: 我目前有以下代码:

RewriteCond %{HTTP_HOST} !^http://www.domain.com/tag/([0-9a-zA-Z]*)/page/([0-9]*)/$
RewriteRule (.*) http://www.domain.com/tag/$1/ [R=301,L]

In this code, if the URL does not exist it redirects to the main tag page, but its not working. 在此代码中,如果URL不存在,则会重定向到主标记页面,但它不起作用。

Does anybody have an hints or solutions on how to solve this problem? 有没有人提供如何解决这个问题的提示或解决方案?

If I understand what you're saying, you are saying that you have a list of rewritten URLs (using mod_rewrite ); 如果我理解你在说什么,你说你有一个重写URL列表(使用mod_rewrite ); some of them exist, some of them don't. 其中一些存在,其中一些不存在。 With the ones that don't exist, you want them to be redirected to a new page location? 对于那些存在的那些,您希望将它们重定向到新的页面位置吗?

The short-answer is, you can't do that within htaccess . 简短的回答是,你不能在htaccess做到这htaccess When you're working with mod_rewrite , your rewritten page names are passed to a controller file that translates the rewritten URL to what page/content it's supposed to display. 当您使用mod_rewrite ,您的重写页面名称将传递到控制器文件,该文件将重写的URL转换为它应显示的页面/内容。

I'm only assuming you're using PHP, and if so, most PHP frameworks (CakePHP, Drupal, LithiumPHP, etc.) can take care of this issue for you and handle custom redirects for non-existing files. 我只是假设你正在使用PHP,如果是这样,大多数PHP框架(CakePHP,Drupal,LithiumPHP等)可以为你处理这个问题并处理不存在的文件的自定义重定向。 If you have a custom-written application, you'll need to handle the redirect within the PHP website and not in the .htaccess file. 如果您有自定义编写的应用程序,则需要在PHP网站内处理重定向,而不是在.htaccess文件中。

A very simple example of this would be: 一个非常简单的例子是:

<?php
function getTag($url) {
    if (preg_match('|/tag/([0-9a-zA-Z]*)/|', $url, $match)) {
        return $match[1];
    }
    return '';
}

function validateUrl($url) {
    if (preg_match('|/tag/([0-9a-zA-Z]*)/page/([0-9]*)/|', $url, $match)) {
        $tag = $match[1];
        $page = $match[2];
        $isValid = // your code that checks if it's a URL/page that exists
        return $isValid;
    }
    return false;
}

if (!validateUrl($_SERVER['REQUEST_URI'])) {
    $tag = getTag($_SERVER['REQUEST_URI']);
    header ('HTTP/1.1 301 Moved Permanently');
    header('Location /tag/' . $tag . '/');
    die();
}

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM