【问题标题】:htaccess - Rewrite all files to index.php except sitemap.xmlhtaccess - 将所有文件重写为 index.php,除了 sitemap.xml
【发布时间】:2018-04-03 06:31:48
【问题描述】:

我正在尝试将每个 php 文件重定向到 index.php,sitemap.xml 除外。问题是sitemap.xml 也被重定向到index.php。 如何将所有php文件重定向到index.php和sitemap.xml到sitemap.php?

重写引擎开启 RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\ [NC] 重写规则 ^ %1 [R=301,L] RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^/?(.*)\.php$ index.php [L,QSA] RewriteRule sitemap.xml sitemap/sitemap.php [L]

【问题讨论】:

  • sitemap.xml 是否作为物理文件存在?
  • 不,它不存在。我从一个名为 sitemap.php 的 php 文件动态生成它

标签: php xml apache .htaccess url-rewriting


【解决方案1】:

您需要一个额外的 RewriteCond 来排除 sitemap.php,否则当请求 sitemap.php 时,它将满足 !-d-f 两个条件,并再次被重写为 index.php

RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\ [NC]
RewriteRule ^ %1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_FILENAME} !/(sitemap.php)/
RewriteRule ^/?(.*)\.php$ index.php [L,QSA]
RewriteRule sitemap.xml sitemap/sitemap.php [L]

【讨论】:

  • 如果您删除 CondPattern 上的斜线后缀,那么这应该“有效”。
【解决方案2】:

sitemap.xml 被重写为 sitemap/sitemap.php,但随后重写过程重新开始(在 .htaccess 中),sitemap/sitemap.php 然后在第二遍被重写为 index.php

对于您希望允许直接访问的任何现有.php 文件,您应该在文件顶部添加一个“例外”。例如:

RewriteRule ^(index|sitemap/sitemap)\.php$ - [L]

这将防止/index.php/sitemap/sitemap.php 被随后的指令处理(并被重写为index.php)。 index.php 目前“有效”只是因为 mod_rewrite 稍后检测到您正在回写自己并忽略第二次重写。


RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\ [NC]
RewriteRule ^ %1 [R=301,L]

旁白:我不确定这应该做什么,但我不认为这是在做你认为它在做什么?事实上,我不认为这是在做任何事情!? CondPattern 上的尾随反斜杠(转义字符)是这里的问题。看起来您正在尝试匹配请求 URL 之后(和协议之前)的 空格,但这不是这里会发生的,在 CondPattern 末尾时间>。 “问题”是 space 也是 Apache 配置文件中的参数分隔符。为了匹配 pattern 末尾的 space,您应该使用 \s(任何空白字符)速记字符类,或者将 CondPattern 在双引号中,或包含协议的前几个字符(例如HTTP)。例如:

  • RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\s
  • RewriteCond %{THE_REQUEST} "^[A-Z]{3,}\s([^.]+) "(如果用双引号括起来,转义空格是可选的)
  • RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\ HTTP

NC 标志大多是多余的,除非您也试图捕获无效请求?任何合法的浏览器请求都会将方法和协议全部大写。

但是,如果这确实匹配(带有尾随空格),那么对于任何不包含 .(字面点)的 URL,您将获得一个重定向循环。因此,无论哪种方式,它看起来都不正确。 (?)

【讨论】:

    猜你喜欢
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多