gpt4 book ai didi

PHP .htaccess -> 漂亮的 url(反向)

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:42:44 24 4
gpt4 key购买 nike

我知道如何重写 URL,例如: www.example.com/index.php?id=1&cat=3www.example.com/1/3/ (管他呢)。我知道。

我不知道的是到底如何更改所有页面中的整个链接以链接到漂亮的 URL。我网站的所有链接都是过时的 (<a href="index.php?id=1&cat=2">),而且有很多。

我想问是否有人有想法或知道如何在用户单击 index.php?id=1 时自动重定向到那个漂亮的 url。 (如果您更改 url 中的标题,几乎就像这个网站 Stackoverflow)。

所以我的推测是...

  1. 用.htaccess读取index.php?id=1&cat=2重写index/1/3,自己又解释了(奇怪)

  2. 一个 php 文件,用于执行 htaccess 重写回原始的重定向...

结论:改变<a href="index.php?id=1&.....">自动转到 index/1/2


已解决

Options +FollowSymLinks
RewriteEngine On
RewriteBase /

##################################
# This turns index.php?id=1&cat=2 into index/1/2 and then back 'transparent' into index.php?id=1&cat=2 if you have old fashioned
# links in your site and don't want to change them :)


# Avoid mod_rewrite infinite loops
# This is critical if you want to use this code

RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule .* - [L]

# Hard-rewrite ("[R]") to "friendly" URL.
# Needs RewriteCond to match original querystring.
# Uses "?" in target to remove original querystring,
# and "%n" backrefs to move its components.
# Target must be a full path as it's a hard-rewrite.
RewriteCond %{QUERY_STRING} ^id=(\d+)&cat=(\d+)$
RewriteRule ^index.php$ http://localhost/index/%1/%2/? [L,R]

# Soft-rewrite from "friendly" URL to "real" URL.
# Transparent to browser.
# Won't re-trigger the above rewrite, though I'm
# not really sure why! The order of the rules
# doesn't seem to make a difference.
RewriteRule ^index/(\d+)/(\d+)/$ index.php?id=$1&cat=$2 [L]

最佳答案

RewriteEngine on

# Prevents browser looping, which does seem
# to occur in some specific scenarios. Can't
# explain the mechanics of this problem in
# detail, but there we go.
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule .* - [L]

# Hard-rewrite ("[R]") to "friendly" URL.
# Needs RewriteCond to match original querystring.
# Uses "?" in target to remove original querystring,
# and "%n" backrefs to move its components.
# Target must be a full path as it's a hard-rewrite.
RewriteCond %{QUERY_STRING} ^id=(\d+)&cat=(\d+)$
RewriteRule ^index\.php$ http://example.com/index/%1/%2/? [L,R]

# Soft-rewrite from "friendly" URL to "real" URL.
# Transparent to browser.
RewriteRule ^index/(\d+)/(\d+)/$ /index.php?id=$1&cat=$2

当然,理想情况下,您只需修复您的链接,然后您只需要软重写。 :)

使用 Apache/2.2.3 测试。我想我编造了术语“硬重写”和“软重写”。

关于PHP .htaccess -> 漂亮的 url(反向),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5573485/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com