htaccess重定向-第一段到PHP文件,第二段作为参数


htaccess Redirect - First Segment to PHP File, Second Segment as Parameter

我的htaccess重定向知识有些薄弱,所以我希望在这里得到一些帮助。

我目前有以下重定向,效果很好:

# remove trailing slash
RewriteRule ^(.*)/$ /$1 [L,R=301]
# redirect to clean URL
RewriteCond /%{REQUEST_FILENAME}.php -f
RewriteRule ^([a-zA-Z0-9_-'s]+)$ /$1.php

这需要一个类似www.mysite.com/aboutwww.mysite.com/about.php 的URL

现在我想保留这种行为,但添加参数(如果适用),例如:

www.mysite.com/about=>www.mysite.com/about.php

www.mysite.com/gallery/1=>www.mysite.com/gallery.php?id=1

如果可能的话,我可能想将这个系统扩展到2个或更多的参数,例如:

www.mysite.com/gallery/1/2=>www.mysite.com/gallery.php?id=1&section=2

所以模式是:

  • 第一个URL段重定向到PHP文件
  • (可选)添加第二段作为id参数
  • (可选)添加第三段作为section参数

试试

# remove trailing slash
RewriteRule ^(.*)/$ /$1 [L,R=301]
# redirect to clean URL
RewriteCond /%{REQUEST_FILENAME}.php -f
RewriteRule ^([a-zA-Z0-9_-'s]+)$ /$1.php
RewriteRule ^([a-zA-Z0-9_-'s]+)/([a-zA-Z0-9_-'s]+)/([a-zA-Z0-9_-'s]+)$ /$1.php?id=$2&section=$3
#RewriteRule ^([a-zA-Z0-9_-'s]+)/([a-zA-Z0-9_-'s]+)/([a-zA-Z0-9_-'s]+)/([a-zA-Z0-9_-'s]+)$ /$1.php?param1=$2&param2=$3&param3=$4 and so on

您应该考虑使用通用路由器。这完全解放了你的重定向使用任何你想要的。

通常路由器规则如下:

RewriteRule ^(.*)$ handler.php?path=$1 [QSA]

如果你想避免通过路由器发送静态文件(如CSS文件和图像),你可以添加-f-d,但在我的情况下,即使是这些文件也会通过我的路由器。

然后在handler.php中检查输入,看看它是否是你知道如何处理的东西,比如:URL是像/about还是像/gallery/[0-9]