这是我想要实现的目标:
我需要从干净的 url 中提取 3 个点并将它们转换为 url 参数。典型的干净 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 中没有文件,电子邮件地址就会被放入文件参数中。
当然,如果我提供页面、字母数字和文件,一切都会完美运行。条件可能会高于所有规则,但我不确定。
最佳答案
这是我认为应该放在 .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/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b080e0b1e09111e093b081455181416" rel="noreferrer noopener nofollow">[email protected]</a> --> /index.php?page=mailbox&<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="39505d044a4c495c4b535c4b794a56175a5654" rel="noreferrer noopener nofollow">[email protected]</a>
/mailbox/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7605030613041c13043605195815191b" rel="noreferrer noopener nofollow">[email protected]</a>/inbox.php
--> /index.php?page=mailbox&<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86efe2bbf5f3f6e3f4ece3f4c6f5e9a8e5e9eb" rel="noreferrer noopener nofollow">[email protected]</a>&file=inbox.php
请注意,如果您不想在文件/目录存在时进行重定向;您需要将以下内容附加到所有规则
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
关于regex - mod_rewrite 带有可选的电子邮件和文件名参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18242061/