You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用.htaccess隐藏站点URL中的子文件夹

Solution to Hide Subfolders in URLs

Here's how you can modify your .htaccess file to achieve the URL simplification you want. The updated code will handle both redirecting old subfolder URLs to the simplified ones and internally rewriting the simplified URLs to the actual subfolder files, while keeping your existing .html removal functionality.

Updated .htaccess Code

RewriteEngine on

# 1. Redirect subfolder-based HTML URLs to simplified version (e.g., /subfolder1/index1.html → /index1)
RewriteCond %{THE_REQUEST} /subfolder(1|2)/([^.]+)\.html [NC]
RewriteRule ^ /%2 [NC,L,R=301]

# 2. Redirect other HTML URLs (like root index.html) to non-HTML version
RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R=301]

# 3. Internally map simplified URLs to subfolder files
RewriteRule ^index1$ subfolder1/index1.html [NC,L]
RewriteRule ^index2$ subfolder2/index2.html [NC,L]

# 4. Handle root request (maps / to index.html)
RewriteRule ^$ index.html [NC,L]

# 5. Fallback: Rewrite non-HTML requests to their HTML counterparts in root (keeps your original functionality)
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]

Breakdown of Each Section

Let's go through what each part does so you understand how it works:

  • Section 1: This catches any incoming requests to subfolder1/filename.html or subfolder2/filename.html and permanently redirects (301) the user to /filename. This ensures anyone using the old subfolder URLs gets sent to the simplified version, which is good for SEO and user experience.

  • Section 2: This keeps your original functionality of redirecting any other HTML URLs (like the root index.html) to their non-HTML equivalents.

  • Section 3: These are internal rewrite rules. When a user visits /index1, the server quietly loads subfolder1/index1.html behind the scenes without changing the URL displayed in the browser. Same for /index2 pointing to subfolder2/index2.html.

  • Section 4: Handles the root domain request (e.g., www.example.com) by loading the root index.html file.

  • Section 5: Your original fallback rule that checks if a non-HTML request has a matching HTML file in the root directory and loads it internally. This preserves your existing functionality for any other HTML files in the root.

Notes

  • We use R=301 (permanent redirect) instead of a temporary R=302 because this is a permanent URL change. This helps search engines update their indexes to the new simplified URLs.
  • If you add more files in the future (e.g., subfolder1/index3.html), you just need to add a new line in Section 3 like RewriteRule ^index3$ subfolder1/index3.html [NC,L].

内容的提问来源于stack exchange,提问作者Anca Vulc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 00:57:32