简体   繁体   English

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

[英]How to use htaccess code for URL rewrite in PHP?

I have a link like below: 我有一个如下链接:

In /country/search.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'] ?>">

When I use the below .htaccess code, it does nothing: 当我使用下面的.htaccess代码时,它什么都不做:

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

It does in the tool: 它在工具中具有以下功能:

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

... but when I click that link it shows old URL again. ...但是当我单击该链接时,它将再次显示旧的URL。

What is the problem here? 这里有什么问题?

I'm generating that .htaccess code using this tool: http://www.generateit.net/mod-rewrite/ 我正在使用此工具生成该.htaccess代码: http : //www.generateit.net/mod-rewrite/

Replace your code with this: 用以下代码替换代码:

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]

I think you misunderstood what the rewrite rules are trying to achieve in this context. 我认为您误解了重写规则在这种情况下想要实现的目标。

Fe this rewrite rule 铁这个改写规则

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

Will ensure that a request to http://example.com/mymethod/myarg will be rewritten to 将确保将对http://example.com/mymethod/myarg的请求重写为

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

When you generate links from within your application you should know how you contstructed the rewrite rules and you have to build the link accordingly. 从应用程序内部生成链接时,您应该知道如何构造重写规则,并且必须相应地构建链接。

Original URL: 原始网址:

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

Ideal URL: 理想网址:

/India/andhra%20Pradesh

And .htaccess code: 和.htaccess代码:

RewriteEngine On 

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM