php - 如何使用 mod rewrite/htaccess 创建带有两个或多个参数的友好 URL?

标签 php regex apache .htaccess mod-rewrite

Mod 重写新手在这里。我想在 URL 中传递两个 URL 参数,但格式更友好。如果用户通过“example.com/blah123/sys”,在这种情况下,我应该能够提取 MySQL 记录“blah123”和模式类型“sys”。这是示例:

网址:

example.com/blah123/sys

在 .htaccess 中,我有:

RewriteEngine On
RewriteRule ^([^/.]+)/?$ index.php?id=$1

如果传递的 URL 是“example.com/blah123”,但不是“example.com/blah123/sys”,则上述方法有效。

我尝试了以下方法,但它不起作用:

RewriteEngine On
RewriteRule ^([^/.]+)/?$/?$ index.php?id=$1?mode=$1

我需要提取第二个参数中传递的“模式”类型。因此,如果用户输入“example.com/blah123/sys”,我应该能够从 URL 中获取值“sys”。我怎样才能做到这一点?我想使用 PHP、MySql、.htacess。

更新: 我当前的 .htaccess:

# Use PHP 5.3
AddType application/x-httpd-php53 .php 
RewriteEngine On
#RewriteRule ^([^/.]+)/?$ index.php?id=$1
RewriteRule ^([^/.]+)/([^/.]+)/?$ index.php?id=$1&mode=$2 [L,QSA]

最佳答案

你的正则表达式是错误的。您不能在输入中让 $ 跟在另一个 $ 之后,因为 $ 表示文本结束。

这条规则应该有效:

RewriteEngine On

# new rule to handle example.com/blah123/sys
RewriteRule ^(\w+)/(\w+)/?$ /index.php?id=$1&mode=$2 [L,QSA]

# your existing rule to handle example.com/blah123
RewriteRule ^(\w+)/?$ /index.php?id=$1 [L,QSA]

关于php - 如何使用 mod rewrite/htaccess 创建带有两个或多个参数的友好 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20277428/

相关文章:

php 从 mySQL 数据库中检索数据到表单中

javascript - 如何在 json 中提供日期格式选项?

php - 多用户应用程序记录锁定 - 最佳方法?

正则表达式以递归方式重命名所有文件,删除字符 "?"命令行后的所有内容

php - LAMP 中的 XAMPP 和 WAMP,哪个最好?

PHP浮点输出格式

javascript - 为什么我的脚本忽略空数组结果?

Javascript 正则表达式仅匹配数字 1 到 11

c# regex 解析 ical 格式的文件并用结果填充对象

mysql - XAMPP 3.2.1 上的 Apache 和 Mysql 未启动