我尝试了在 StackOverflow 上找到的几种解决方案,但它们似乎都不起作用。
首先,在文档根目录上,我有 .htaccess 文件 和 index.php 检测语言并重定向到 /fr/
目录或 /en/
目录。
然后我有 index.html 文件和一个名为“pages”的目录,其中它们都是我的页面。这样,所有网址都像 http://example.com/fr/index.html或 http://example.com/fr/pages/a.html .
我愿意:
隐藏“index.html”。如果我没记错的话,这个解决方案是 很好:
RewriteEngine On RewriteRule ^index\.html$ / [R=301,L]
隐藏html 和php 扩展。我用过这个并且有效 适用于 php 但不适用于 html...不知道为什么。
RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^\.]+?)/?$ $1.php [NC,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^\.]+?)/?$ $1.html [NC,L]
隐藏页面目录(我不介意/fr/或/en/目录 显示)以便 URL 将像这样(最后):http://example.com/fr/a
这是我的结构
├── fr
| └── index.html
| └── pages
| └──a.html
| └──b.html etc
├── en
| └── index.html
| └── pages
| └──a.html
| └──b.html etc
├── .htaccess
└── index.php
最佳答案
Hide "index.html". If I'm not mistaken, this solution is fine :
RewriteEngine On RewriteRule ^index\.html$ / [R=301,L]
您说“很好”,但是,这似乎与您的网站结构无关,所以它似乎没有任何作用?该指令假定您在文档根目录中有 index.html
。但是您不想删除 index.html
和 index.php
而不管它们出现在 URL 路径中的什么位置吗?例如,像这样的东西:
RewriteCond %{THE_REQUEST} /index\.(html|php)
RewriteRule (.*)index\.(html|php)$ /$1 [R=301,L]
条件是防止某些服务器配置上的重定向循环。
这还要求 index.php
和 index.html
都包含在您的 DirectoryIndex 中。
Hide html and php extension. I used this and it worked fine for php but not html...don't know why.
RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^\.]+?)/?$ $1.php [NC,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^\.]+?)/?$ $1.html [NC,L]
这是一个冲突。您有相同的 RewriteRule
pattern - 那么哪个应该“获胜”?第一个指令总是“赢”,第二个指令永远不会发生。
但是...您的“站点结构”不完整吗?您的站点结构在文档根目录中显示单个 index.php
(无论如何都会重定向到 /
)- 中没有 .php
文件子目录,那么为什么需要检查?
如果您确实在整个站点结构中混合了 .html
和 .php
文件,并且没有可辨别的模式,那么您将需要执行文件系统检查以查看如果文件在重写之前存在(这是相对昂贵的)。例如:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^.]+?)/?$ $1.php [NC,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^.]+?)/?$ $1.html [NC,L]
在字符类中使用时不需要反斜杠转义点(以匹配文字点),因为在字符类中使用时它没有特殊含义(与正则表达式中的其他地方相反)。
但是,如果有一个模式,那么这可以大大改善。
- Hide pages directory (I don't mind if
/fr/
or/en/
directories are shown) so that URL will be like this (in the end) :http://example.com/fr/a
为了澄清,您必须首先链接到 example.com/fr/a
。
然后将所有请求重写到 /pages
子目录(并在同一 Action 中附加 .html
扩展名),您可以执行如下操作:
RewriteRule ^(fr|en)/([^/.]+)$ /$1/pages/$2.html [L]
关于php - .htaccess 文件/隐藏子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53035260/