【问题标题】:How to create a friendly URL with two or more arguments using mod rewrite / htaccess?如何使用 mod rewrite / htaccess 创建具有两个或多个参数的友好 URL?
【发布时间】:2013-12-15 03:48:11
【问题描述】:

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]

【问题讨论】:

    标签: php regex apache .htaccess mod-rewrite


    【解决方案1】:

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

    这条规则应该有效:

    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]
    

    【讨论】:

    • id=$1?mode=$1 你确定吗,这应该是一个问号作为参数之间的分隔符?看来,那个 PO 出错了。
    • 第二个? 应该是&
    • @AndreasBjørn:谢谢伙计,再次对问题中的错误复制/粘贴表示歉意。
    • @anubhava 感谢您的回复。现在,“example.com/blah123/sys”似乎工作,但不是“example.com/blah123”。问题是用户可以输入两种 URL 类型,即“example.com/blah123/sys”或“example.com/blah123”。有没有办法让这两种情况都起作用?
    • @Gandalf:你确定"example.com/blah123" 不起作用。我使用这些规则尝试了两个 URI,并且都运行良好。您可能还有其他一些相互冲突的规则。你能发布你现有的 .htaccess 有问题吗?
    猜你喜欢
    • 2017-11-08
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 2019-04-30
    • 2011-09-23
    • 1970-01-01
    • 2018-09-20
    • 2020-02-13
    相关资源
    最近更新 更多