Auto Redirect www to non www and http to https using Global in MVC ASP.net

Thảo luận trong 'Lập Trình Website MVC5 & MVC6' bắt đầu bởi admin, 21/9/18.

  1. admin
    Tham gia ngày:
    22/5/13
    Bài viết:
    4,883
    Đã được thích:
    1,193
    Điểm thành tích:
    113
    Giới tính:
    Nam
    Tự động / Auto Redirect www to non www and http to https using Global.asax in MVC ASP.net có rất nhiều cách khác nhau, Nhưng để chuyển từ có www sang không dùng www hoặc sử dụng chuyển hướng từ http sang https khi dùng tập tin Global.asax không phải ai cũng biết.

    auto-redirect-www-to-non-www-and-http-to-https.jpg

    Ví dụ: bạn muốn chuyển web từ www.itseovn.com thành itseovn.comhttp://itseovn.com sang https://itseovn.com thì làm như thế nào?

    Cách chuyển như sau: bạn truy cập vào file Global.asax trong Solution web của bạn. Add thêm đoạn code sau vào nhé.
    Mã:
    protected void Application_BeginRequest()
    {
        //Chuyển từ www sang none www vd: www.itseovn.com thành itseovn.com    
        if (!HttpContext.Current.Request.IsLocal && HttpContext.Current.Request.Url.Host.StartsWith("www"))
        {
            var Builder = new UriBuilder(Request.Url);
            Builder.Host = Request.Url.Host.Remove(4); //xóa www. trong hosting
            Response.RedirectPermanent(Builder.ToString(), true);
        }
    
        //chuyển http to https vd: http://itseovn.com thành https://itseovn.com
        if (HttpContext.Current.Request.IsSecureConnection == false && HttpContext.Current.Request.IsLocal == false)
        {
            Response.RedirectPermanent("https://" + Request.ServerVariables["HTTP_HOST"] + HttpContext.Current.Request.RawUrl);
        }
    }
    Bạn nên đọc tiếp bài sau để tạo trọn bộ SEO trong file Global cho web MVC của bạn:
     
    Cảm ơn đã xem bài:

    Auto Redirect www to non www and http to https using Global in MVC ASP.net

    Chỉnh sửa cuối: 21/9/18


Chủ để tương tự : Auto Redirect
Diễn đàn Tiêu đề Date
Lập Trình Website MVC5 & MVC6 Auto Keep Session Alive Timeout in MVC, tự động giữ thời gian sống session MVC 6/4/20
Lập Trình Website MVC5 & MVC6 Custom 404 error is not redirecting to Global.asax in MVC C# 3/7/20
Lập Trình Website MVC5 & MVC6 Redirect URL chữ hoa thường lẫn lộn sang chữ thường ToLower() MVC ASP.net 21/9/18
Lập Trình Website MVC5 & MVC6 RedirectToAction with parameter trong MVC C# ASP.NET 2/9/18
Lập Trình Website MVC5 & MVC6 Redirect http sang https sử dụng mô hình MVC trong IIS Asp.net 27/7/18