使用.htaccess隐藏站点URL中的子文件夹
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.htmlorsubfolder2/filename.htmland 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 loadssubfolder1/index1.htmlbehind the scenes without changing the URL displayed in the browser. Same for/index2pointing tosubfolder2/index2.html.Section 4: Handles the root domain request (e.g.,
www.example.com) by loading the rootindex.htmlfile.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 temporaryR=302because 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 likeRewriteRule ^index3$ subfolder1/index3.html [NC,L].
内容的提问来源于stack exchange,提问作者Anca Vulc

