在 .htaccess 文件的正则表达式中包含 URL 个编码字符

Including URL encoded characters in regex for .htaccess file

我需要在 .htaccess 文件的正则表达式中包含 URL 编码符号,用于不同语言的特殊字符。

我有以下内容,其中包括 space 个字符 %20

RewriteRule ^search/([0-9a-zA-Z\s-]+)/?$ search.php?search= [L,NC,QSA]

但我需要能够包含像 õ 这样的字符,即 %C3%B5

基本上我需要它来包含任何 URL 编码的字符和 % 字符。

您可以在站点根目录 .htaccess 中使用此代码:

Options -MultiViews
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^search/([^/]+)/?$ search.php?search= [L,NC,QSA]
  • 您需要关闭 MultiViews 选项,因为您的php 文件名与起始URI 组件相同。选项 MultiViews(参见 http://httpd.apache.org/docs/2.4/content-negotiation.html)由 Apache's content negotiation module 使用,它在 之前 mod_rewrite 运行并使 Apache 服务器匹配文件的扩展名。因此,如果 /search 是 URL 那么 Apache 将提供 /search.php.
  • 需要
  • RewriteCond 以确保您不匹配站点根目录中名为 search/ 的目录。

您可以使用 [^\/] negated character class:

^search/([^\/]+)/?$

匹配

  • ^ - 字符串开头
  • search/ - 文字子串
  • ([^\/]+) - 捕获第 1 组(它匹配的内容用 </code> 引用):除 <code>/
  • 之外的任何 1+ 个字符
  • /? - 一个可选的 /
  • $ - 字符串结尾。