首页 > 解决方案 > htaccess:隐藏文件夹并隐藏子文件夹链接中的文件扩展名

问题描述

我有这些文件夹结构:

domain.com/pages/index.php
domain.com/pages/about/a-page.php
domain.com/pages/service/service-type/service-name.php

我希望他们像:

domain.com/index
domain.com/about/a-page
domain.com/service/service-type/service-name

这些是我到目前为止所拥有的:

#remove folder name on link e.g. https://example.com/pages/file.php will become https://example.com/file.php 
RewriteEngine On
RewriteRule ^$ pages/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ pages/$1

#remove php file extension-e.g. https://example.com/file.php will become https://example.com/file 
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [NC,L] 

老实说,我只是从教程中复制了这个..并尝试了与我的类似问题的其他建议,这些是我能达到的最接近目标的建议。

标签: .htaccess

解决方案


在看了很多 htaccess 教程之后,我发现它应该是

RewriteEngine On

#remove php file extension-e.g. https://example.com/file.php will become https://example.com/file 
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [NC,L] 

#remove folder name on link e.g. https://example.com/pages/file.php will become https://example.com/file.php 
RewriteRule ^$ pages/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ pages/$1 [NC,L] 

所以我不应该忘记重写规则中的 [L] 部分,因为它不会读取其他不适合它的重写条件。


推荐阅读