apache - 解释htaccess规则?

标签 apache .htaccess mod-rewrite

我在过去的一个小时里通过搜索、复制和粘贴等制作了这个 .htaccess 文件。

它确实像我想要的那样工作。

然而我不明白。

有人可以用外行的话来一步一步地把这里发生的事情记下来。

RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^/?(.*)$ /$1.php [L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^\ ]+)\.php
RewriteRule ^/?(.*)\.php$ /$1 [L,R=301]

RewriteCond %{THE_REQUEST} ^.*/index
RewriteRule ^(.*)index.php$ /$1 [R=301,L]

如果有任何提示,请将它们扔在那里。

最佳答案

RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
^www\.example\.com$ anchor ^$表示这是 HTTP_HOST 中的完整字符串,之前或之后都没有。因此,如果随请求传递的域名匹配www.example.com确切地说,整个 URI (.*)重定向到 example.com ,从而剥离 www.从前面。
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^/?(.*)$ /$1.php [L]

一个 -f标志到 RewriteCond测试第一个参数是否是实际存在的文件。在这种情况下,它测试 REQUEST_FILENAME 的值,这将是像 file 这样的 URI 的最后一部分( example.com/directory/file )通过添加 .php 作为 PHP 文件存在扩展到测试参数。

所以,如果 file.php实际存在,请求不存在file在这里用 $1.php 默默地重写到其对应的 PHP 文件中.所以如果 /directory/notexists没有对应的 directory/notexists.php文件,它不会被重写。
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^\ ]+)\.php
RewriteRule ^/?(.*)\.php$ /$1 [L,R=301]
THE_REQUEST包含完整的 GET/POST请求最初发送的浏览器,如 GET /index.php .所以这里匹配到的和上一个块是类似的。
  • ^[A-Z]{3,9}第一个匹配动词 GETPOST等,但不会捕获它以供重用
  • /([^\ ]+)然后捕获 / 之后的所有内容直到下一个空格,比如 indexGET /index.php .
  • \.php字面匹配

  • 好的,那么下面的RewriteRule把那个 index捕获到 %1符合上述条件,实际上重定向浏览器以删除 .php扩展,所以浏览器的结束 URL 看起来像 /index .

    换句话说,如果浏览器请求 /directory/file.php.php扩展,它将用户重定向到 /directory/file脱掉 .php .
    RewriteCond %{THE_REQUEST} ^.*/index
    RewriteRule ^(.*)index.php$ /$1 [R=301,L]
    

    而这个匹配任何包含 /index 的内容在原始请求中,但不必位于 URI 的开头。换句话说,/directory/index会匹配,就像 /directory/subdir/index.php 一样.无论匹配什么,它都会被重定向到索引部分之前的任何内容。让我们分解一下:
  • ^(.*)匹配开头的任何内容到 $1
  • index.php .. 出现在上面匹配的任何内容之后

  • 然后重定向到 $1组件,所以 URL 像 /directory/subdir/index.php如果浏览器直接请求,将被重定向到指向更干净的 URL:/directory/subdir/没有 index.php出现在地址栏中。

    关于apache - 解释htaccess规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18236838/

    相关文章:

    regex - url 中存在空格的 mod 重写问题

    windows - Mod_rewrite 在 Windows 和 Ubuntu 上有不同的结果

    php - 头部的 Magento CSS 和 JS 包括来自文档根目录?

    apache - 多域设置上的 htaccess : other domains don't work

    linux - 如何在不设置 777 权限的情况下使 apache 读写用户目录

    php - .htaccess 中的 HeaderName 不使用 .php 扩展名

    php - 如何实现像 www.example.com/username 这样的 url 以重定向到 www.example.com/user/profile.php?uid=10?

    php - htaccess 重定向隐藏 php 扩展或传递参数

    Apache SSL 使用 openssl 将 itermediateCA.cer 转换为 crt

    java - 使用Maven构建Hadoop src时出错