Ahmed iqbal
Ahmed iqbal

Reputation: 597

htaccess 404 error conditional code for 301 redirect

I have paginated URLs that look like 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.

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.

Does anybody have an hints or solutions on how to solve this problem?

Upvotes: 0

Views: 799

Answers (1)

newfurniturey
newfurniturey

Reputation: 38456

If I understand what you're saying, you are saying that you have a list of rewritten URLs (using 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. 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.

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. If you have a custom-written application, you'll need to handle the redirect within the PHP website and not in the .htaccess file.

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();
}

?>

Upvotes: 2

Related Questions