I have just setuped ssl for my dmain and host. I want to limit my site to https://www.example.com
. https://www.example.com
。
If the any user tried to open http://example.com
, www.example.com
, example.com
or https://example.com
he must be redirected to https://www.example.com
The redirection must be for the domain name only. The rest of any URL would remains as is.
For example: if user opened example.com/dir1/page1.aspx
he must be redirected to https://www.example.com/dir1/page1.aspx
I want to do it using IIS rewrite rules.
I solved this problem by adding this code to web.config
file on the root directory of the domain.
www
what ever it is http
or https
以www
http
或https
second rule matches the url if it with www
but it https
但 https
<system.webServer> <rewrite> <rules> <rule name="Redirect from non www" stopProcessing="true"> <match url=".*" /> <conditions> <add input="{HTTP_HOST}" pattern="^example.com$" /> </conditions> <action type="Redirect" url="https://www.example.com/{R:0}" redirectType="Permanent" /> </rule> <rule name="Redirect from non https" stopProcessing="true"> <match url=".*" /> <conditions> <add input="{HTTPS}" pattern="^OFF$" /> <add input="{HTTP_HOST}" pattern="^www.example.com$" /> </conditions> <action type="Redirect" url="https://www.example.com/{R:0}" redirectType="Permanent" /> </rule> </rules> </rewrite> </system.webServer>
Add this in your global.asax file if you donot have control over iis or using a shared hosting where the hosting company doesnt allow u to change the settings.
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Request.IsSecureConnection.Equals(false) && HttpContext.Current.Request.IsLocal.Equals(false))
{
Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"] + HttpContext.Current.Request.RawUrl);
}
}
EDITED:
For canonical tag (www.example.com) you dont need to make any changes in your code. there is a setting given for it in your plesk panel/odin panel (even in shared hosting) to select the default url for you application.
It will automatically redirect your site to www.example.com
The settings in under hosting settings of your website. select the preferred domain option to www
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.