URL Rewrite - PHP & Apache


URL Rewrite - PHP & Apache

我有这样的链接

<li><a href="search.php?domainid=5&cat=electronic">Electronic</a></li>

如何将其更改为

<li><a href="electronic.html">Electronic</a></li>

我有50多个类别。

我正在使用Apache网络服务器和PHP 5.5。需要动态 URL 重写 SEO 友好的 URL。

<li><a href="search.php?domainid=5&cat=electronic">Electronic</a></li>

这需要

<li><a href="electronic.html">Electronic</a></li>

<li><a href="search.php?domainid=13&cat=gifts">Gifts</a></li>

这需要

<li><a href="gifts.html">Gifts</a></li>

<li><a href="search.php?domainid=4&cat=food">Food</a></li>

这需要

<li><a href="food.html">Food</a></li>

<li><a href="search.php?domainid=11&cat=home-decore">Home Decore</a></li>

这需要

<li><a href="home-decore.html">Home Decore</a></li>

<li><a href="search.php?domainid=3&cat=hotels-travels">Hotels & Travel</a></li>

这需要

<li><a href="hotels-travels.html">Hotels & Travel</a></li>

等等...

这是完整的解决方案

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule ^([a-z]*)'.html /search.php?domainid=5&cat=$1 [L,QSA]
</IfModule>

它只有几行,但这里发生了很多事情,所以让我们分解一下每个小点的作用

<IfModule mod_rewrite.c>

这一行只是打开一个节(块(,指示 Apache 只应在加载指定模块时才执行其中的指令。在本例中,mod_rewrite模块。

  RewriteEngine on

非常简单,只是打开 url 重写以防万一它还没有

  RewriteRule ^/([a-z]*)'.html /search.php?domainid=5&cat=$1 [L,QSA]

这是所有工作发生的地方,它有点复杂,所以我将进一步分解它。一、重写规则剖析

重写规则模式替换 [标志]

因此,让我们先看一下模式

^/([a-z]+)'.html

RewriteRule 模式是正则表达式 - 如果你还不熟悉这些,恐怕你必须做一些独立的研究,因为它们在这里是一个很大的主题。但我要说的是,这种模式旨在匹配从根开始的任何 URI,并且具有一个或多个连续的小写字母字符,后跟 .html 。所以它会匹配所有这些

/electronic.html
/electronic.html?referrer=facebook
/analog.html
/somethingelse.html

任何这些都不匹配

/category/electronic.html # Because it's not root relative
/cat5.html                # Because of the number
/something-else.html      # Because of the hyphen
/Electronic.html          # Because of the capital E

如您所见,正则表达式模式非常明确和敏感,因此您需要充分了解类别名称的性质,以便编写正确的 RewriteRule 模式。

在此模式中要注意的另一件事是连续字母字符周围的括号 - 这将创建一个"捕获的子组",可以在 RewriteRule 的替换部分中引用,我们需要,所以让我们看看下一个

/search.php?domainid=5&cat=$1

这告诉重写引擎获取匹配的 url,并根据上述模式在内部重写它们。看到$1了吗?这是我们在模式中捕获的子组,因此它将被捕获的角色替换。

最后一部分是[标志]

  • L的意思只是"最后",它告诉mod_rewrite不要再次尝试重写URL
  • QSA是"查询字符串追加",它将确保请求的 URL 中的查询字符串数据将保留到重写的 URL 中。例如,/electronic.html?referrer=facebook将被重写为/search.php?domainid=5&cat=electronic&referrer=facebook

就是这样!您几乎肯定需要对其进行修改以 100% 满足您的需求,但我希望这足以让您入门。

编辑

以下是一些与不同类别名称匹配的替代模式

  • ^/([a-z-]+)'.html 允许连字符
  • ^/([a-zA-Z]+)'.html 允许大写字母
  • ^/([a-z0-9]+)'.html 允许数字
  • ^/([a-zA-Z0-9-]+)'.html 允许以上所有操作

一个非常简洁的例子.htaccess可能包含:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^.]+)'.html$ search.php?domainid=5&cat=$1 [L]

编辑:关于domainid参数,您有几个选择:

  • 添加更多规则以从 %{HTTP_HOST} 转换为域映射到的任何 ID。
  • 修改search.php以从说$_SERVER['HTTP_HOST']中找出答案。

后者可能是理智的做法。