如何在IIS中配置URL重写规则实现站点子目录访问时自动跳转至index.html
Hi there! Nice work getting the root redirect up and running—let's expand that rule to cover all your subdirectories easily.
Your initial rule only targets the root (^$ matches an empty URL path), but we can adjust the regex to catch any directory path that ends with a slash (like /subdir/, /team/marketing/, etc.) and redirect it to the corresponding index.html dynamically.
Step 1: Update or Add a URL Rewrite Rule
You can either modify your existing "Index Request" rule or create a new one. Here's the adjusted rule that covers both the root and all subdirectories:
<rule name="Index Request (All Directories)" enabled="true" stopProcessing="true"> <match url="^(.*/)?$" /> <conditions logicalGrouping="MatchAll"> <!-- Optional: Prevent redirect loops by skipping actual files --> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> </conditions> <action type="Redirect" url="{R:1}index.html" redirectType="Temporary" /> </rule>
Let's Break This Down:
match url="^(.*/)?$": This regex handles two key scenarios:- The root path (empty string,
^$) - Any subdirectory path ending with a slash (like
/subdir/—the(.*/)?captures the full directory path including the trailing slash)
- The root path (empty string,
{R:1}: This is a backreference to the captured directory path. For the root, it’s empty, so the redirect goes toindex.html; for/subdir/, it becomessubdir/, leading tosubdir/index.html.- Optional Condition: The
IsFilecheck ensures we don’t redirect users who access actual files directly (like/index.htmlor/styles.css), avoiding unnecessary loops. redirectType: UseTemporary(302) for testing, or switch toPermanent(301) once you confirm the rule works (this helps with search engine indexing).
Why This Works Better Than Just Default Documents
You mentioned setting index.html as the default document—and that’s great for internal serving (IIS quietly returns index.html without changing the URL). But your client wants a visible URL redirect (the address bar updates to show /subdir/index.html), which is exactly what this rewrite rule delivers. The two can coexist without conflict!
Pro Tip for Flexibility
Avoid hardcoding your domain in the redirect URL—use IIS server variables to build it dynamically instead:
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}index.html" redirectType="Temporary" />
{HTTP_HOST} automatically pulls your domain name, so you won’t have to edit the rule if your site moves to a new domain later.
Test it out by visiting /subdir/—you should be redirected straight to /subdir/index.html instantly, just like the root path.
内容的提问来源于stack exchange,提问作者Grant1979

