Regex .htaccess如何删除文件扩展名和索引文件

Regex .htaccess如何删除文件扩展名和索引文件,regex,apache,.htaccess,mod-rewrite,url-rewriting,Regex,Apache,.htaccess,Mod Rewrite,Url Rewriting,我试图通过.htaccess实现一些功能,但一直遇到问题。在你告诉我我需要更好的研究,并且在这个或其他论坛上已经有了解决方案之前,请知道我已经做了。在来这里之前,我总是试着自己想办法解决问题,但这件事真的难住我了。我所做的一切都只是部分奏效。这里的任何帮助或教育都将不胜感激 我的站点具有以下简单结构: (root) | index.html | .htaccess | |___portal-folder | index.php | home

我试图通过.htaccess实现一些功能,但一直遇到问题。在你告诉我我需要更好的研究,并且在这个或其他论坛上已经有了解决方案之前,请知道我已经做了。在来这里之前,我总是试着自己想办法解决问题,但这件事真的难住我了。我所做的一切都只是部分奏效。这里的任何帮助或教育都将不胜感激

我的站点具有以下简单结构:

(root)
 |   index.html
 |   .htaccess
 |
 |___portal-folder
      |     index.php
      |     home.php
      |
      |_____admin-folder
             |     index.php
我希望实现以下目标:

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

  • 如果用户导航到完整的URL
    site.com/index.html
    site.com/portal folder/index.php
    我希望用户在浏览器中分别看到
    site.com
    site.com/portal folder/
    ,则同样适用

  • 删除浏览器中所有文件的文件扩展名。例如,导航到
    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版

    采用以下方式:

    DirectoryIndex.html index.php
    重新启动发动机
    #从外部将/dir/file.php重定向到/dir/file并可选地删除索引
    重写COND%{U请求}\s/+(.*?/)?(?:索引|)(\s+)(?:\.php |\.html)?[/\s?][NC]
    重写规则^/%1%2[R=301,L,NE]
    #删除尾部斜杠
    重写cond%{REQUEST_FILENAME}-D
    重写条件%{REQUEST_URI}^(+)/+$
    重写规则^%1[R=301,NE,L]
    #将/dir/file内部转发到/dir/file.php
    重写cond%{REQUEST_FILENAME}-D
    重写cond%{DOCUMENT_ROOT}/$1.php-f
    重写规则^(+?)/?$$1.php[L]
    
    非常感谢您!现在这个很好用!虽然有一件事,但这没什么大不了的。我注意到,如果用户导航到
    site.com/index
    它不会切换到
    site.com
    如果用户切换到
    site.com/index.html
    它会工作,请检查我最新编辑的规则。它负责
    /index
    alsoThanks@anubhava,但是你发布的更新对我不起作用。结果我试图浏览的每一页都出现了错误。我最终继续使用你的原始版本。这很奇怪,因为我在发布之前已经测试过了。