mod_rewrite包含可选的电子邮件和文件名参数

时间:2013-08-14 20:50:33

标签: regex .htaccess mod-rewrite

以下是我想要完成的事情:

我需要从一个干净的网址中提取3个点并将它们转换为url参数。典型的干净网址如下所示:

http://mysite.com/page/someAlphaNumeric-OR-emailAddress/file.html

或:

http://mysite.com/page/file.html

或:

http://mysite.com/page/someAlphaNumeric-OR-emailAddress

第一个变量将始终为字母数字,第二个变量是可选的,可能包含字母数字或电子邮件地址,第三个变量(如果提供电子邮件/字母数字,则也是可选的)将始终为文件名。

我为第二个变量试了很多不同的东西,但问题是文件和电子邮件地址似乎都在争吵。 到目前为止似乎最接近解决方案的代码:

RewriteEngine On
RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z0-9-z\-]+)$ index.php?page=$1&id=$2 [L,QSA]
RewriteRule ^([a-zA-Z0-9]+)$ index.php?page=$1 [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z0-9-z\-]+)/.*$ index.php?page=$1&id=$2&file=$0 [L,QSA]
RewriteRule ^([a-zA-Z0-9]+)/.*$ index.php?page=$1&file=$0 [L,QSA]

如果我提供了一个页面,同时提供了电子邮件地址和文件名,则只为文件名分配一个参数。如果没有url中的文件,则电子邮件地址会进入文件参数。

当然,如果我提供一个页面,字母数字和文件,一切都很完美。条件可能高于所有规则,但我不确定。

1 个答案:

答案 0 :(得分:2)

以下是我认为应该放在.htaccess

中的内容
RewriteEngine On

# /page
RewriteRule ^(\w+)$ index.php?page=$1 [L,QSA]

# /page/file.html
RewriteRule ^(\w+)/([\w.-]+\.[a-z]{3,4})$ index.php?page=$1&file=$2 [L,NC,QSA]

# /page/id OR /page/email
RewriteRule ^(\w+)/(\w+|[\w.-]+@[\w-]+\.[\w.-]+)$ index.php?page=$1&id=$2 [L,QSA]

# /page/id/file.html OR /page/email/file.html
RewriteRule ^(\w+)/(\w+|[\w.-]+@[\w-]+\.[\w.-]+)/([\w.-]+\.[a-z]{3,4})$ index.php?page=$1&id=$2&file=$3 [L,NC,QSA]

以上规则重定向

/mailbox --> /index.php?page=mailbox
/mailbox/login.php --> /index.php?page=mailbox&file=login.php

/mailbox/SuperJer123 --> /index.php?page=mailbox&id=SuperJer123
/mailbox/superjer@so.com --> /index.php?page=mailbox&id=superjer@so.com

/mailbox/superjer@so.com/inbox.php
                   --> /index.php?page=mailbox&id=superjer@so.com&file=inbox.php

请注意,如果您不希望在文件/目录存在时进行重定向;你需要在下面附加所有规则

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d