如何在ASP中将短URL重定向/重写至原始长URL?
Hey there, I’ve worked through similar URL rewrite headaches for ASP.NET-based link shorteners before, so let’s break down how to get your shrtn.aspx handling those short links properly.
First: Make Sure the URL Rewrite Module is Installed
This is such a common gotcha—if IIS doesn’t have the URL Rewrite Module enabled, none of your rewrite rules will work at all. Check this in IIS Manager: look for "URL Rewrite" in the server/site features list. If it’s missing, install it via the IIS Web Platform Installer.
Correct Web.config Rewrite Rule
Your goal is to route any short URL like http://localhost:9909/snKcxi to shrtn.aspx?key=snKcxi. Here’s a tested rule set to add to your web.config under the <system.webServer> section:
<rewrite> <rules> <!-- Skip actual files/directories to avoid breaking static content --> <rule name="Skip Existing Resources" stopProcessing="true"> <match url=".*" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" /> </conditions> <action type="None" /> </rule> <!-- Rewrite short links to shrtn.aspx with the key parameter --> <rule name="Short Link Rewrite" stopProcessing="true"> <match url="^([a-zA-Z0-9]+)$" /> <action type="Rewrite" url="shrtn.aspx?key={R:1}" /> </rule> </rules> </rewrite>
What this does:
- The first rule ensures requests for real files (like CSS/JS) or directories aren’t rewritten—so your static content still works.
- The second rule matches any URL path that’s just a string of letters/numbers (your short key), then rewrites it to
shrtn.aspxwith the key passed as a query string parameter.
Update shrtn.aspx Logic
Make sure your code correctly pulls the key and handles the redirect (and edge cases):
protected void Page_Load(object sender, EventArgs e) { string shortKey = Request.QueryString["key"]; // Handle empty or invalid key requests if (string.IsNullOrEmpty(shortKey)) { Response.StatusCode = 404; Response.Write("Invalid short link."); Response.End(); return; } // Query your database for the original URL string originalUrl = FetchOriginalUrlFromDB(shortKey); if (!string.IsNullOrEmpty(originalUrl)) { // Use 301 redirect for SEO (permanent), or 302 if links might change later Response.RedirectPermanent(originalUrl, true); } else { // Key not found in database Response.StatusCode = 404; Response.Write("Short link not found."); Response.End(); } } // Replace this with your actual database lookup method private string FetchOriginalUrlFromDB(string key) { using (var conn = new SqlConnection("YourDatabaseConnectionString")) { conn.Open(); var cmd = new SqlCommand("SELECT OriginalUrl FROM ShortLinks WHERE ShortKey = @Key", conn); cmd.Parameters.AddWithValue("@Key", key); return cmd.ExecuteScalar()?.ToString(); } }
Extra Checks to Fix 404s
- Verify IIS Site Path: Double-check that your site’s physical path points to the folder where
shrtn.aspxlives. - Disable Friendly Errors: Temporarily turn off IIS’s "Friendly HTTP Errors" to see a more detailed error message that might pinpoint the issue.
- Test the Regex: Use the URL Rewrite Module’s "Test Pattern" tool in IIS Manager to confirm your short key (like
snKcxi) matches the rule’s regex. - Check for Conflicting Rules: If you have other rewrite rules in
web.config, make sure they don’t override this one—thestopProcessing="true"attribute helps prevent that.
Once you implement these changes, test your short link again—you should no longer get a 404, and shrtn.aspx will handle the redirect smoothly.
内容的提问来源于stack exchange,提问作者ace

