【问题标题】:.htaccess how to remove file extensions and index files.htaccess 如何删除文件扩展名和索引文件
【发布时间】:2021-01-20 22:46:56
【问题描述】:

我正在尝试通过 .htaccess 实现一些目标,但一直遇到问题。在您告诉我我需要进行更好的研究并且在此或其他论坛上已经有解决方案之前,请知道我已经这样做了。在来这里之前,我总是尝试自己解决问题,但这确实让我感到难过。我尝试过的一切都只是部分奏效。在这里的任何帮助或教育将不胜感激。

我的网站结构简单:

(root)
 |   index.html
 |   .htaccess
 |
 |___portal-folder
      |     index.php
      |     home.php
      |
      |_____admin-folder
             |     index.php

我希望实现以下目标:

  1. 当用户导航到任何基本目录时,例如site.com 或site.com/portal-folder/,他们在浏览器中看不到索引文件名index.html 或index.php。

  2. 如果用户导航到完整的 URL site.com/index.html 或 site.com/portal-folder/index.php 我希望用户在浏览器中分别看到 site.com 或 site.com/portal-folder/。

  3. 去除浏览器中所有文件的文件扩展名。因此,例如导航到site.com/portal-folder/home.php 将在浏览器中显示为site.com/portal-folder/home

以下代码我正在使用某种作品,但我得到了奇怪的行为。例如:

  • 导航到site.com/portal-folder/index 不会删除索引文件名并在浏览器中显示为site.com/portal-folder/index 而不是site.com/portal-folder/

  • 导航到site.com/portal-folder/ 不会删除索引文件名并在浏览器中显示为site.com/portal-folder/index.php。

  • 导航到site.com/portal-folder/index.php 将用户带回根site.com

  • 导航到site.com/portal-folder/home 可以正常工作,但导航到site.com/portal-folder/home.php 不会去掉 .php 扩展名。

  • 导航到site.com 可以正常工作,但导航到site.com/index.html 不会删除索引文件名。

    RewriteEngine On
    
    DirectoryIndex index.html  index.php
    
    # remove trailing slash
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{THE_REQUEST} \s(.+?)/+[?\s]
    RewriteRule ^(.+?)/$ /$1 [R=301,L]
    
    # To internally forward /dir/file to /dir/file.php
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{DOCUMENT_ROOT}/$1.php -f
    RewriteRule ^(.+?)/?$ /$1.php [L]
    

服务器信息:Apache 版本 2.4.46

【问题讨论】:

    标签: regex apache .htaccess mod-rewrite url-rewriting


    【解决方案1】:

    这样吧:

    DirectoryIndex index.html index.php
    
    RewriteEngine On
    
    # To externally redirect /dir/file.php to /dir/file and optionally remove index
    RewriteCond %{THE_REQUEST} \s/+(.*?/)?(?:index|(\S+?))(?:\.php|\.html)?[/\s?] [NC]
    RewriteRule ^ /%1%2 [R=301,L,NE]
    
    # remove trailing slash
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} ^(.+)/+$
    RewriteRule ^ %1 [R=301,NE,L]
    
    # To internally forward /dir/file to /dir/file.php
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{DOCUMENT_ROOT}/$1.php -f
    RewriteRule ^(.+?)/?$ $1.php [L]
    

    【讨论】:

    • 非常感谢!现在效果很好!虽然有一点,但也不是什么大不了的事。我注意到如果用户导航到site.com/index,它不会切换到site.com,如果他们通过切换到site.com导航到site.com/index.html,它确实可以工作
    • 请查看我最新编辑的规则。它也照顾/index
    • 感谢@anubhava,但您发布的更新对我不起作用。它最终在我尝试访问的每个页面上都出错了。我最终继续使用您的原始版本。
    • 这很奇怪,因为我在发布之前已经测试过了。
    猜你喜欢
    • 2019-01-03
    • 2023-04-04
    • 1970-01-01
    • 2012-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    相关资源
    最近更新 更多