简体   繁体   中英

How to redirect everything via Web.config or C# to https://www. version of the site?

I have an ASP.NET website hosted on GoDaddy. I need to redirect (301) every request to https://www.example.com/whatever

So for example:

This is a piece of cake on Linux or cPanel hostings. But I don't know how to do this on GoDaddy (I asked support, but they don't seem to know nothing...). I guess it's easy to do with IIS, but GoDaddy doesn't give you IIS access.

So is there a way to do it via Web.config or C#? Preferably web.config

Check out this article of mine, which provides a number of different options for avoiding duplicate URLs in your ASP.NET site: Techniques for Preventing Duplicate URLs in Your Website . I've summarized the various techniques below, but see the article for a more in-depth treatment, as well as for a sample ASP.NET website demo.

Issuing Permanent Redirects from ASP.NET

You can check the incoming URL for every request in your Global.asax file's Application_BeginRequest event handler. If the URL is missing the leading www. you can append it and do a permanent redirect to the new URL.

protected void Application_BeginRequest(object sender, EventArgs e)
{
   if (Request.Url.Authority.StartsWith("www"))
      return;

   var url = string.Format("{0}://www.{1}{2}",
               Request.Url.Scheme,
               Request.Url.Authority,
               Request.Url.PathAndQuery);

   Response.RedirectPermanent(url, true);
} 

Rewriting URLs Into Canonical Form Using IIS 7's URL Rewrite Module

If your website is hosted by IIS7 and Microsoft's URL Rewrite Module is installed, then you can add rewriting rules in your Web.config file. I don't have any sites hosted with GoDaddy, so I have no idea if they use IIS7 (I imagine they do) or if they have the URL Rewrite Module installed. Check with support.

Presuming these prerequisites are met, you would use the following configuration:

<configuration>
   ...

   <system.webServer>
      <rewrite>
         <rules>
            <rule name="Canonical Host Name" stopProcessing="true">
               <match url="(.*)" />

               <conditions>
                  <add input="{HTTP_HOST}" pattern="^yoursite\.com$" />
               </conditions>

               <action type="Redirect" url="http://www.yoursite.com/{R:1}" redirectType="Permanent" />
            </rule>
         </rules>
      </rewrite>
   </system.webServer>
</configuration>

Rewriting via a Third-Party Application

Many web hosting companies have a third-party URL rewriting application installed, such as ISAPI_Rewrite. I don't know if GoDaddy has this, you'd need to check with support. But this may be another option.

Telling Search Engine Spiders Your Canonical Form In Markup

Rather than worrying about redirecting users to the www. version, you could just let users arrive at your site however they want to, but add markup to your page to tell the search engines the canonical form of your URLs.

To specify the canonical URL simply add a <link> element in the <head> portion of the web page. The way this works as is follows - add the following markup to the <head> sections of those pages in your website that you want the search engines to consider all the same URL:

<link rel="canonical" href="canonical_url" /> 

If you do a View/Source on Stackoverflow.com you'll see this <link> tag in place. This is a great way to ensure that duplicate URLs in your site - eg, www.yoursite.com/foo.aspx and yoursite.com/foo.aspx are treated as the same entry in the search engine's index.

Happy Programming!

Thanks Scott for the excellent answer! This was very helpful.

Here is a mod to the Application_BeginRequest() code that 1) uses ordinal string comparisons for speed, 2) accommodates localhost and 3) highlights an asymmetric side-effect.

protected void Application_BeginRequest(object sender, EventArgs e)
{
    /**
     *  Note:
     *    Since Url.Authority always returns an all lowercase string, we can use 
     *    StringComparison.Ordinal (instead of OrdinalIgnoreCase) for www and 
     *    localhost checks.
     *  
     *  Ordinal rationale:
     *    "Use comparisons with StringComparison.Ordinal or 
     *    StringComparison.OrdinalIgnoreCase for better performance"
     *    see http://msdn.microsoft.com/en-us/library/dd465121.aspx#choosing_a_stringcomparison_member_for_your_method_call
     */
    if (Request.Url.Authority.StartsWith("www", StringComparison.Ordinal))
        return;

    /**
     * Avoid redirection on localhost.
     */
    if (Request.Url.Authority.StartsWith("localhost", StringComparison.Ordinal))
        return;

    /**
     * Because Uri.Authority is always lowercase, this code has the side-effect of 
     * enforcing a lowercase authority (e.g., http://NoisyKeys.com/About is 
     * converted to http://www.noisykeys.com/About).  This is asymmetric with 
     * previous conditionals.  To attain symmetry, we probably want to use 
     * Request.Url.OriginalString instead of Request.Url.Authority.
     */
    var url = string.Format("{0}://www.{1}{2}", 
        Request.Url.Scheme,
        Request.Url.Authority,
        Request.Url.PathAndQuery);

    Response.RedirectPermanent(url, true);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM