URL重写 - PHP&阿帕奇

时间:2016-07-28 17:46:49

标签: php apache .htaccess url-rewriting

我有像

这样的链接
<li><a href="search.php?domainid=5&cat=electronic">Electronic</a></li>

如何将其更改为

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

我有超过50个类别。

我正在使用Apache Web服务器和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>

依旧......

2 个答案:

答案 0 :(得分:1)

这是完整的解决方案

<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

非常简单,只需打开网址重写,以防它已经不是

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

这是所有工作发生的地方,而且有点复杂,所以我会进一步细分。首先,the anatomy of a rewrite rule

  

RewriteRule 模式替换[flags]

所以,让我们先来看一下模式

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

RewriteRule模式是regular expressions - 如果你还不熟悉那些我害怕你将不得不做一些独立的研究,因为它们要覆盖很大的主题这里。但我要说的是,此模式旨在匹配从根开始的任何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模式。

在这种模式中需要注意的另一件事是连续的字母字符周围的括号 - 它创建一个&#34;捕获的子组&#34;可以在RewriteRule的 Substitution 部分引用,我们需要让我们看看下一个

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

这告诉重写引擎采用匹配的url并根据上述模式在内部重写它们。查看$1?这是我们在模式中获得的捕获子组,因此它将被捕获的字符所取代。

最后一部分是 [flags]

  • L只是意味着&#34;最后&#34;告诉mod_rewrite不再尝试重写URL
  • QSA是&#34;查询字符串追加&#34;这将确保请求的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允许以上所有

答案 1 :(得分:0)

真正的例子.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']

后者可能是理智的事情。

相关问题