以下是几个网址示例:
domain.com/?view=home&action=update
domain.com/?view=home&page=1&action=update
domain.com/?view=home&action=update&page=2&sort=desc
domain.com/?view=home&sort=desc&page=2&action=update
如何让我的.htaccess将URL(上述任何格式)重写为以下结构:
domain.com/home/1/desc/update
get参数的数量在不同情况下是不同的,以及参数的顺序。
此外,我需要能够在PHP中重写后才能 $ _ GET 。
应用程序将使用以下密钥作为查询字符串:
view, item, page, sort, dir, action.
所有这些都是可选的,我可能需要稍后再添加一些。
我尝试了所有这些,没有工作:
RewriteRule ^(.*)$ index.php/$1 [L]
RewriteRule ^/([^?]*)$ /index.php?$1 [NC,L,QSA]
RewriteRule ^([^?]*)$ /index.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ index.php?params=$1 [NC]
感谢。
答案 0 :(得分:1)
而不是重写为domain.com/home/1/desc/update
,我觉得您希望用户能够点击这样的链接:domain.com/home/1/desc/update
,并将该网址内部重写为查询表单,以便您可以在PHP中提取变量(用户将看不到查询URL)。
您向我们举了一个包含四个变量的网址示例:domain.com/home/1/desc/update
,但在其他地方,您说还有两个变量:dir
和item
。
为了从domain.com/home/1/desc/update
这样的网址中可靠地提取参数,它必须是可靠的格式。因此,
domain.com/home/1/desc/update/dir_value/item_value
domain.com/view/home/page/1/sort/desc/action/update
一旦你做出了这个选择,就可以重写,但不是在那之前。
答案 1 :(得分:1)
get参数的数量在不同的情况下是不同的,如 以及参数的顺序。
这是一个问题。 mod_rewrite
的问题是,您需要某种结构来将domain.com/home/1/desc/update
的优秀SEO友好网址过滤为类似domain.com/?view=home&page=1&sort=desc&action=update
的内容。所以这样的东西可以用来捕获任何或所有段,但是按照特定的顺序:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-z0-9]+)/?([^/]*)$ index.php?q=$1&$2 [QSA]
RewriteRule ^([a-z0-9]+)/([a-z0-9]+)/([a-z0-9]+)/([a-z0-9]+)/?$ index.php?view=$1&sort=$2&page=$3&action=$4 [L]
RewriteRule ^([a-z0-9]+)/([a-z0-9]+)/([a-z0-9]+)/?$ index.php?view=$1&sort=$2&page=$3 [L]
RewriteRule ^([a-z0-9]+)/([a-z0-9]+)/?$ index.php?view=$1&sort=$2 [L]
RewriteRule ^([a-z0-9]+)/?$ index.php?view=$1 [L]
如果您将以下代码放在index.php
中:
echo '<pre>';
print_r($_GET);
echo '</pre>';
输出结果为:
Array
(
[view] => home
[sort] => 1
[page] => desc
[action] => update
)
但如果你是积极的,你需要处理随机结构化的SEO友好URL,那么这条规则应该有效:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url_path=$1 [L]
现在不会重定向任何内容,但它会捕获/home/1/desc/update
的整个路径并将其设置在$_GET
数组中,并使用名为url_path
的键。然后,您可以在index.php
中检查该变量中的内容,如下所示:
echo '<pre>';
print_r($_GET);
echo '</pre>';
$segments = explode('/', $_GET['url_path']);
echo '<pre>';
print_r($segments);
echo '</pre>';
输出就是这样:
Array
(
[url_path] => home/1/desc/update
)
Array
(
[0] => home
[1] => 1
[2] => desc
[3] => update
)