如何使用 htaccess 代码在 PHP 中重写 URL


How to use htaccess code for URL rewrite in PHP?

我有一个链接如下:

/country/search.php

<a href="<?php echo 'index.php?departments='.$value['department_id'].'&towns='.$value['town_id'].'&type='.$value['type_id'].'&id='.$value['id'] ?>">

当我使用以下.htaccess代码时,它什么也不做:

RewriteEngine On
RewriteRule ^([^/]*)/([^/]*)/([^/]*)/([^/]*)$ /country/index.php?departments=$1&towns=$2&type=$3&id=$4 [L] 

它在工具中执行:

http://example.com/0/0/4/122

。但是当我单击该链接时,它再次显示旧URL。

这里有什么问题?

我正在使用此工具生成.htaccess代码:http://www.generateit.net/mod-rewrite/

将你的代码替换为:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
# external redirect from actual URL to pretty URL
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}'s/+(index'.php|)'?departments=([^'s&]*)&towns=([^'s&]*)&type=([^'s&]*)&id=([^'s&]*) [NC]
RewriteRule ^ %1/%2/%3/%4/%5? [R=301,L]
# internal forward from pretty URL to actual URL
RewriteRule ^([^/]*)/([^/]*)/([^/]*)/([^/]*)/?$ /country/index.php?departments=$1&towns=$2&type=$3&id=$4 [L,QSA]
我想

你误解了重写规则在这种情况下试图实现的目标。

F.e. 此重写规则

RewriteRule ^([^/]*)/([^/]*)$ /app.php?method=$1&arg=$2

将确保对 http://example.com/mymethod/myarg 的请求将被重写为

http://example.com/app.php?method=mymethod&arg=myarg

当您从应用程序内部生成链接时,您应该知道如何构建重写规则,并且必须相应地构建链接。

原始网址:

href="news.php?state="<?php echo $sql_res['state']?>"&country="<?php echo $sql_res['country']?>

理想网址:

/India/andhra%20Pradesh

和.ht访问代码:

RewriteEngine On 
RewriteRule ^([^/]*)/([^/]*)$ /news.php?country=$1&state=$2 [L]