[英].htaccess; Too many redirects if two different redirects in .htaccess
[英]Handle .htaccess redirects with different parameters?
我想将不进入目录的URL重定向到一个脚本(例如script1.php),以及具有另一个脚本(script2.php)类别的URL。 基本上我想做这样的事情: http : //www.test.com/user1 - > http://www.test.com/script1.php?username=user1其中script1.php获取用户名并显示适合该用户的页面。 我有这个部分使用此代码:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ script1.php?username=$1 [L,QSA]
现在的问题是我还希望有描述性的产品网址,例如http://www.test.com/clothes/jackets/cool-red-jacket-25重定向到http://www.test.com /items.php?category=clothes&subcategory=jackets&id=25 。 我有一些代码也适用于此:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?([a-zA-Z-]+)/([a-zA-Z-]+)/.*-A([0-9-.]+)\.php$
script2.php?category=$1&subcategory=$2&id=$3 [L]
我遇到的问题是组合这两种类型的重定向。 第一个重定向始终重定向到自己的页面,第二个重定向永远不会到达。 是否有可能将这两种方式结合起来? 基本上我需要像htaccess这样的东西,如果可能的话
if(!urlHasDirectories) {
redirect to script1.php?username=$username;
} else {
redirect to script2.php?category=$category&subcategory=subcategory&id=$id;
}
让我们来看看基本的正则表达式,我们将使用Regex101。 的.
是任何字符, *
是前一个字符/分组的量词零次或多次。 所以你的第一个正则表达式, RewriteRule ^(.*)$ script1.php?username=$1 [L,QSA]
表示重写任何以任何东西开头的东西,并以scripts1.php
。 那不是你想要的。
演示: https : //regex101.com/r/hK0xY3/1
使用正则表达式最好尽可能具体。
我会为用户制定规则:
RewriteRule ^(user\d+)$ script1.php?username=$1 [L,QSA]
演示: https : //regex101.com/r/hK0xY3/4
+
是另一个量词,这里意味着一个或多个,所以如果不需要数字,你可以将它改为*
。
你说你想要一个正则表达式来查找路径中是否有/
。 我认为最好告诉正则表达式要看什么,但这是可能的:
^.+?\/
演示: https : //regex101.com/r/hK0xY3/3
使用这种方法,虽然任何目录请求将被重定向...
对于seo友好的url使用这个像:
RewriteRule ^user/([a-zA-Z0-9_-]+)$ user.php?username=$1
RewriteRule ^item/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ items.php?category=$1&subcategory=$2&id=$3
您需要在.htaccess文件中将更具体的规则放在更高的位置,以便首先进行匹配。 一般使用它。
遗憾的是,与其他请求匹配的最通用规则(。*)可用于更多不同的操作。
.com/john-doe // for user profile
.com/my-new-article // for showing article and so on
如果您想要组合所有这些变体,您需要决定在您的应用程序级别使用哪个操作(配置文件或显示文章)。 例如mvc架构中的控制器。 它可以通过条件轻松完成。
if(userExists($userName))
// showing template for user profile etc...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.