我的根目录中有一个名为
pages
的文件夹,我希望在访问时隐藏该文件夹。目前,我的网址如下所示:www.foo.com/pages/page.html
我想删除 URL 中的文件夹名称
pages
,但仍将用户定向到该文件夹。如何使用 .htaccess
文件执行此操作?为了清楚起见,我希望最终 URL 如下所示:www.foo.com/page.html
我查看了一些 StackOverflow 答案,并且很难理解如何编辑 .htaccess 文件来进行此调整。到目前为止,我的
.htaccess
文件如下所示:
RewriteEngine on
RewriteCond %{REQUEST_URI} !^pages/
RewriteRule ^(.*)$ /$1 [L]
如何使用 .htaccess 将
www.foo.com/pages/page.html
更改为 www.foo.com/page.html
?
你实际上需要 2 条规则来管理它:
301/302
如果 URL 已经有 /pages/
(通常是浏览器/搜索结果中的缓存 URL)/pages/
,以便从您的主机提供正确的页面您可以将这些规则放在站点根目录 .htaccess 中:
RewriteEngine On
# To externally redirect /pages/pages.html to /pages.html
RewriteCond %{THE_REQUEST} \s/+pages/([^\s?]*)[\s?] [NC]
RewriteRule ^ /%1 [R=302,NE,L]
## To internally rewrite /pages.html to /pages/pages.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/pages/ [NC]
RewriteRule .* pages/$0 [L]