Adding “301 Redirect” to a large number of files in IIS 6

filesiis-6redirect

I am trying to create a permanent (301) redirect all the files in a directory to a single file within that directory.

For instance, if a user visits site.com/directory/randompage.html, I want them to be redirected to site.com/directory/index.html.

I have tried putting a redirect on the directory and then overriding the redirect on the file level, but IIS does not appear to allow this.

Is there a way to accomplish what I am after? or do I have to create a redirect on a file by file basis?

Best Answer

For attempted access to files that don't exist you can put a custom 404 error on the directory that redirects the user to the URL for the file you'd like them to access.

If there are other files in that directory you'll have to put redirects on them on a file-for-file basis. That's just the way it is, unfortunately. If you have a lot of files you could script the metabase modification to add the redirect.

Edit:

If you can modify the NTFS ACLs on all those files to disallow the user from reading them, you could also drop a custom 401.3 error page on the directory, too.

If not, then try this:

@echo off
SET SOURCE_DIR=C:\path-to-directory-in-filesystem
SET ADSUTIL=cscript C:\inetpub\adminscripts\adsutil.vbs
SET METABASE_PATH=W3SVC/####/ROOT/path/to/site/directory
SET REDIRECT_URL=/foo/foo.txt

for /f "usebackq delims=" %%i in (`dir /b %SOURCE_DIR%`) do (
 %ADSUTIL% CREATE %METABASE_PATH%/%%i
 %ADSUTIL% SET %METABASE_PATH%/%%i/KeyType "IIsWebFile"
 %ADSUTIL% SET %METABASE_PATH%/%%i/HttpRedirect "%REDIRECT_URL%, PERMANENT"
)

Set the SOURCE_DIR to the physical path in the filesystem of the directory with the files to be made into redirects. ADSUTIL is probably set right if you're a stock IIS 6 install. METABASE_PATH needs to refer to the site identifier number (### in the sample, get it from the IIS management console for your site) and the path under the root (leave /ROOT/ there-- that needed). Finally, REDIRECT_URL needs to be the URL (can be absolute or relative to the root of the site).