【问题标题】:htaccess redirect all pages to subdirectory except roothtaccess 将所有页面重定向到除根目录之外的子目录
【发布时间】:2022-01-11 00:40:13
【问题描述】:

我的根目录中有这些文件,在页面内我有 php 文件,例如 projects.php,我尝试编写 .htaccess 规则以获取文件,例如 xxx.com/projects 从 / 打开文件pages/projects.php 并与以下内容一起使用

RewriteEngine On

RewriteCond %{ENV:REDIRECT_STATUS} . [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

# No file extension on request then append .php and rewrite to subdir
RewriteCond %{REQUEST_URI} /(.+)
RewriteRule !\.[a-z0-4]{2,4}$ /pages/%1.php [NC,L]

# All remaining requests simply get rewritten to the subdir
RewriteRule (.*) /pages/$1 [L]

我的问题是当我转到根 xxx.com 而不是打开 index.php 它的打开页面目录时,但如果我明确地转到 xxx.com/index.php 它可以工作。 我不希望 index.php 显示在 url 我需要从我的规则中排除根并使其打开 index.php 而 url 保持 xxx.com

【问题讨论】:

  • "从我的规则中排除根目录并使其打开 index.php" - 在文档根目录中打开 index.php/pages/index.php?

标签: php regex apache .htaccess mod-rewrite


【解决方案1】:
# All remaining requests simply get rewritten to the subdir
RewriteRule (.*) /pages/$1 [L]

要排除“根”被重写为/pages/(并从根提供index.php),您可以简单地将最后一条规则中的量词从*(0 或更多)更改为+( 1 个或更多) - 使其不匹配对根的请求(.htaccess 中的空 URL 路径)。

换句话说:

RewriteRule (.+) /pages/$1 [L]

顺便说一句,您已经通过在 CondPattern 中使用 + 在前面的规则/条件 中完成了类似的操作,即。 RewriteCond %{REQUEST_URI} /(.+).

【讨论】:

    【解决方案2】:

    我想到了另一个解决方案:

    RewriteEngine On
    
    RewriteBase /
    
    # Hide the "pages" directory and all PHP files from direct access.
    RewriteRule ^pages\b|\.php$ - [R=404]
    
    # Rewrite clean-URL pages to the PHP files inside the "pages" directory:
    # If the request isn't a file.
    RewriteCond %{REQUEST_FILENAME} !-f
    # If the request isn't a folder.
    RewriteCond %{REQUEST_FILENAME} !-d
    # If the PHP page file exists.
    RewriteCond %{DOCUMENT_ROOT}/pages/$0.php -f
    # /your-page?param=foo is rewritten to /pages/your-page.php?param=foo
    # The L flag isn't suffisient because the rewrite rule to protect PHP files
    # above will take over in the second loop over all the rewrite rules. To stop
    # here we can use the newly END flag which stops completely the rewrite engine.
    RewriteRule ^.*$ pages/$0.php [END,QSA]
    

    你想隐藏index.php。这可以通过 404 错误来完成。 所以你可以这样做:

    RewriteRule ^index\.php - [R=404]
    

    但您可能还希望避免有人请求/pages 列出所有PHP 文件或直接访问/pages/your-page.php。所以我使用了一个匹配目录和PHP文件扩展名的正则表达式(这里只有小写,但你可以使用\.(?i)php,其中(?i)启用大小写insensitive标志)。

    然后,对于重写本身,我将捕获带有 ^.*$ 的 URL,该 URL 将在 $0 反向引用中可用,然后可以在重写规则本身和重写条件中使用。

    如果请求不是目录或现有文件,那么我们必须检查生成的重写 URL 是否实际上是 pages 目录中的现有 PHP 文件。

    我使用了QSA 标志,以便您将查询参数保留在结果 URL 中。然后,PHP 脚本可以通过$_GET 轻松访问它们。如果您不使用此标志,我希望您也可以通过检查其他一些环境变量来获取它们。我还必须使用类似于LEND 标志用于Last 标志,但完全停止执行重写规则。如果您改用L 标志,问题是您将收到404 错误,因为/pages/your-page.php 将匹配重写规则以隐藏PHP 文件,因为重写规则的整个过程是第二次运行。仅当输入 URL 不再被重写规则更改时,重写引擎循环才会停止。是的,我花了很长时间才明白重写规则不会像配置文件中显示的那样只运行一次!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-04
      • 2012-06-19
      相关资源
      最近更新 更多