如何将所有index.html文件重定向至对应目录根路径?
Hey there! Let's get that index.html redirection sorted out for you. The goal is to turn URLs like https://www.example.com/contact/index.html into https://www.example.com/contact/—keeping the directory path intact, just stripping off the index.html part. Here's how to implement this across common server and hosting setups:
Apache (Using .htaccess)
If you're running Apache, add these rules to your .htaccess file in the root of your site:
RewriteEngine On # Match any URL ending with index.html, capture the directory path RewriteCond %{REQUEST_URI} ^(.*/)index\.html$ [NC] # Redirect to the captured directory path (permanent 301 redirect) RewriteRule ^ %1 [R=301,L]
[NC]makes the match case-insensitive (soIndex.htmlorINDEX.HTMLalso get redirected)R=301sets a permanent redirect, which is best for SEO and browser cachingLtells Apache to stop processing further rules once this one matches
Nginx
For Nginx, add this rewrite rule inside your server block in your configuration file:
# Redirect requests for index.html to their parent directory rewrite ^(.*/)index\.html$ $1 permanent;
The permanent flag here also sets a 301 redirect. The regex captures everything before index.html and redirects to that path.
Static Site Hosts (Netlify/Vercel)
If you're using a static site host like Netlify or Vercel, here's how to set it up:
Netlify
Create a _redirects file in your site's root with this line:
/*/index.html /:splat/ 301!
The ! at the end ensures it's a "force" redirect, even if the destination path exists.
Vercel
Add this to your vercel.json file:
{ "redirects": [ { "source": "/:path*/index.html", "destination": "/:path*/", "permanent": true } ] }
Quick Tip
When testing, you might want to use a temporary 302 redirect first (change R=301 to R=302 in Apache, permanent to redirect in Nginx, or 301 to 302 in Netlify/Vercel). Once you confirm everything works as expected, switch back to 301 to avoid caching issues during testing.
内容的提问来源于stack exchange,提问作者Ardian

