[英]htaccess 404 error conditional code for 301 redirect
我的分页网址看起来像http://www.domain.com/tag/apple/page/1/
如果不存在诸如http://www.domain.com/tag/apple/page/*2/
的URL,或者page/2
不存在,我需要代码将其重定向到诸如http://www.domain.com/tag/apple/
的页面http://www.domain.com/tag/apple/
这将是主要的标签页面。
我目前有以下代码:
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]
在此代码中,如果URL不存在,则会重定向到主标记页面,但它不起作用。
有没有人提供如何解决这个问题的提示或解决方案?
如果我理解你在说什么,你说你有一个重写URL列表(使用mod_rewrite
); 其中一些存在,其中一些不存在。 对于那些不存在的那些,您希望将它们重定向到新的页面位置吗?
简短的回答是,你不能在htaccess
做到这htaccess
。 当您使用mod_rewrite
,您的重写页面名称将传递到控制器文件,该文件将重写的URL转换为它应显示的页面/内容。
我只是假设你正在使用PHP,如果是这样,大多数PHP框架(CakePHP,Drupal,LithiumPHP等)可以为你处理这个问题并处理不存在的文件的自定义重定向。 如果您有自定义编写的应用程序,则需要在PHP网站内处理重定向,而不是在.htaccess
文件中。
一个非常简单的例子是:
<?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.