htaccess简化并删除了斜杠的需要

时间:2013-08-19 18:50:50

标签: .htaccess mod-rewrite url-rewriting friendly-url

我正在写我的第一个htaccess,并希望帮助清理它并理解它。我遇到的第一个问题是多个参数。我目前的设置如下:

Options +FollowSymLinks

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !/(_modules|css|files|ico|img|js)/
RewriteRule ^([^/]*)$ index.php?p1=$1 [L]

RewriteCond %{REQUEST_FILENAME} !/(_modules|css|files|ico|img|js)/
RewriteRule ^([^/]*)/([^/]*)$ index.php?p1=$1&p2=$2 [L]

RewriteCond %{REQUEST_FILENAME} !/(_modules|css|files|ico|img|js)/
RewriteRule ^([^/]*)/([^/]*)/([^/]*)$ index.php?p1=$1&p2=$2&p3=$3 [L]

RewriteCond %{REQUEST_FILENAME} !/(_modules|css|files|ico|img|js)/
RewriteRule ^([^/]*)/([^/]*)/([^/]*)/([^/]*)$ index.php?p1=$1&p2=$2&p3=$3&p4=$4 [L]

有没有办法简化此操作以处理最多4个参数,所有这些参数都是可选的?这让我想到了下一个问题,如果你需要在参数之后有一个尾部斜杠,除非你使用所有4个参数。

简而言之,我希望我的网址看起来像这样......

http://www.example.com/home
http://www.example.com/home/
http://www.example.com/blog/i-am-a-title
http://www.example.com/blog/i-am-a-title/
http://www.example.com/varable1/varable2/varable3/varable4
http://www.example.com/varable1/varable2/varable3/varable4/

我将非常感谢您提供的任何帮助。

2 个答案:

答案 0 :(得分:3)

嗯,这是一个实验,它可以像你说的那样工作,但我相信可能有更好的方法来做到这一点:

RewriteCond %{REQUEST_FILENAME} !/(index\.php|_modules|css|files|ico|img|js)/
RewriteRule ^(([^/]*)/?)(([^/]*)/?)(([^/]*)/?)(([^/]*)/?)$ /index.php?p1=$2&p2=$4&p3=$6&p4=$8 [L]

基本上我每个条目都添加一个额外的组,因此您可以安全地排除不存在的组。

因此第一个元素是必需的,$2,第二个元素变为$4,第三个元素变为$6,最后一个元素变为$8

(([^/]*)/?)这基本上意味着,对于外部群组和内部群组而言,任何与/结束或不与/结束的内容都不是/

更简化规则:

RewriteCond %{REQUEST_FILENAME} !/(index\.php|_modules|css|files|ico|img|js)/
RewriteRule ^([^/]*|)/?([^/]*|)/?([^/]*|)/?([^/]*|) /index.php?p1=$1&p2=$2&p3=$3&p4=$4 [L]

答案 1 :(得分:1)

只要您不介意会有空白参数,您就可以对所有参数使用预测:

RewriteCond %{REQUEST_FILENAME} !/(index\.php|_modules|css|files|ico|img|js)
RewriteRule ^(?:([^/]+)|)(?:/([^/]+)|)(?:/([^/]+)|)(?:/([^/]+)|) index.php?p1=$1&p2=$2&p3=$3&p4=$4 [L]

这些是可选的问题是你的规则将循环一次,这使得第一个捕获组index.php。为避免这种情况,您需要在条件中添加index.php作为exlusion的一部分。