大网数据广告活动
网站运营与故障问答

Hide subfolders in URL with .htaccess

· 52CE 我爱测

I have a URL structure like this: example.com/this/is/nice/index.php and I want achieve this: example.com/this/index.php How can I add a rule to hide the /is/ and /nice/ subfolders ?

问题原文

原帖链接 · nellyserver · CC BY-SA 4.0

I have a URL structure like this: example.com/this/is/nice/index.php

and I want achieve this: example.com/this/index.php

How can I add a rule to hide the /is/ and /nice/ subfolders ?

已采纳解答

原帖链接 · MrWhite · CC BY-SA 4.0

This assumes you have already changed all the internal links on your site to be of the form /this/index.php (or /this/<something>?), ie. #3 in @Stephen's comment above.

For your specific example, you would add something like the following, using mod_rewrite, to the top of the root .htaccess file (requires Apache 2.4):

RewriteEngine On

# A) Redirect "/this/is/nice/index.php" to "/this/index.php"
RewriteRule ^(this)/is/nice/(index\.php)$ /$1/$2 [R=301,L]

# B) Rewrite "/this/index.php" to "/this/is/nice/index.php"
RewriteRule ^(this)/(index\.php)$ $1/is/nice/$2 [END]

The $1 and $2 backreferences contain the value of the corresponding captured subgroup in the preceding RewriteRule pattern (first argument). In this example, that just saves having to repeat "this" and "index.php".

For a more generic solution that rewrites /this/<anything> to /this/is/nice/<anything> (and redirects vice-versa) then use something like the following instead:

# A) Redirect "/this/is/nice/<anything>" to "/this/<anything>"
RewriteRule ^(this)/is/nice/(.*) /$1/$2 [R=301,L]

# B) Rewrite "/this/<anything>" to "/this/is/nice/<anything>"
RewriteRule ^(this)/(.*) $1/is/nice/$2 [END]

Note that this rewrites everything, including any static assets - which may or may not be a problem depending on your scenario (not stated in the question). eg. /this/images/myimage.jpg would be rewritten to /this/is/nice/images/myimage.jpg, regardless of whether /this/images/myimage.jpg exists or not.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2022-06-20)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。