简体   繁体   English

将子域重定向到MVC Core中的区域

[英]Redirect subdomain to area in mvc core

It's takes many time from my day, 我这一天要花很多时间

I have windows server 2016 as my server other side I develop my site in MVC core 2.2 我将Windows Server 2016作为服务器另一端,我在MVC Core 2.2中开发我的网站

OK

Try redirect form admin.mysite.com to mysite.com/admin when user write admin.mysite.com as url Redirect to mysite.com/admin 尝试重定向形式admin.mysite.commysite.com/admin当用户写admin.mysite.com作为URL重定向到mysite.com/admin

Test many ways: 测试很多方法:

  1. use re-write in IIS whis this pattern: Area and subdomain routing 在IIS中使用以下模式进行重写: 区域和子域路由

      <rules> <rule name="Rewrite sub-domain to dir"> <match url="^admin.*$" /> <conditions> <add input="{HTTP_HOST}" pattern="^admin\\.mysite\\.com$" /> </conditions> <action type="Rewrite" url="mysite.com/admin/{R:0}" /> </rule> </rules> </rewrite> 
  2. use this way https://www.azurecurve.co.uk/2011/12/how-to-rewrite-a-sub-domain-to-a-directory-in-iis/ enter link description here 使用这种方式https://www.azurecurve.co.uk/2011/12/how-to-rewrite-a-sub-domain-to-a-directory-in-iis/ 在此处输入链接描述

public class AreaRouter : MvcRouteHandler, IRouter
     {
   public new async Task RouteAsync(RouteContext context)
   {
       string url = context.HttpContext.Request.Headers["HOST"]; 
       var splittedUrl = url.Split('.');

       if (splittedUrl.Length > 0 && splittedUrl[0] == "admin")
       {
           context.RouteData.Values.Add("area", "Admin");
       }

       await base.RouteAsync(context);
    }
   }

but OP ways not work 但是OP方式不起作用

UPDATE: 更新:

        // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        //services.Configure<SmtpConfig>(options => Configuration.GetSection("SmtpConfig").Bind(options));
        //services.Configure<AntiDosConfig>(options => Configuration.GetSection("AntiDosConfig").Bind(options));
        services.Configure<AntiXssConfig>(options => Configuration.GetSection("AntiXssConfig").Bind(options));
        //services.AddDNTCommonWeb();
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });



         var connection = @"Server=*.*.*.*;Database=...;Integrated Security=false;Initial Catalog=...;User ID=...;Password=...;";
        services.AddDbContext<myContext>(options =>
          options.UseSqlServer(connection));
        services.AddSession();
        services.AddDistributedMemoryCache();

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddRoles<IdentityRole>()
            .AddRoleManager<RoleManager<IdentityRole>>()
            .AddDefaultTokenProviders()
            .AddDefaultUI(UIFramework.Bootstrap4)
         .AddEntityFrameworkStores<myContext>();




        services.Configure<IdentityOptions>(options =>
        {
            // Password settings.
            options.Password.RequireDigit = true;
            options.Password.RequireLowercase = true;
            options.Password.RequireNonAlphanumeric = true;
            options.Password.RequireUppercase = true;
            options.Password.RequiredLength = 6;
            options.Password.RequiredUniqueChars = 1;

            // Lockout settings.
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
            options.Lockout.MaxFailedAccessAttempts = 5;
            options.Lockout.AllowedForNewUsers = true;

            // User settings.
            options.User.AllowedUserNameCharacters =
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
            options.User.RequireUniqueEmail = false;
        });

        services.ConfigureApplicationCookie(options =>
        {
            // Cookie settings
            options.Cookie.HttpOnly = true;
            options.ExpireTimeSpan = TimeSpan.FromMinutes(20);

            options.LoginPath = "/Identity/Account/Login";
            options.AccessDeniedPath = "/Identity/Account/AccessDenied";
            options.SlidingExpiration = true;
        });

        services.AddElmah(options => options.Path = "elm");





        services.AddScoped<IPostService, PostService>();
        services.AddScoped<IContactRepository, ContactReposiory>();
        services.AddScoped<ICounterRepository, CounterRepository>();
        services.AddScoped<ICommentRepository, CommentRepository>();
        services.AddScoped<IAntiXssService, AntiXssService>();
        services.AddScoped<IHtmlReaderService, HtmlReaderService>();
        services.AddScoped<Model.Counter>();
        services.AddMvc()
            .AddRazorPagesOptions(options =>
            {
              //  options.Conventions.AuthorizePage("/Contact");
                options.Conventions.AuthorizeAreaFolder("admin","/post");
                options.Conventions.AuthorizeAreaFolder("admin","/");
                options.Conventions.AuthorizeAreaPage("Identity", "/Account/register");
                //options.Conventions.AllowAnonymousToPage("/Private/PublicPage");
                //options.Conventions.AllowAnonymousToFolder("/Private/PublicPages");
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        //app.UseAntiDos(); 

        app.UseSession();
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();
        app.UseAuthentication();
        app.UseMiddleware(typeof(VisitorCounterMiddleware));
        app.UseMvc();
    }

for tracing request to IIS I enabled it but dont get any error on request for like admin.mysite.com, , i got error but not related to request like this 为了将请求跟踪到IIS,我启用了它,但是在请求时没有得到任何错误,例如admin.mysite.com,我得到了错误,但与这样的请求无关

<!-- saved from url=(0014)about:internet -->
<failedRequest url="http://mysitte.com:80/PostDetails/Post/102/index.html"
           siteId="12"
           appPoolId="mysitte.com"
           processId="3424"
           verb="GET"
           remoteUserName=""
           userName=""
           tokenUserName="NT AUTHORITY\IUSR"
           authenticationType="anonymous"
           activityId="{80000027-0000-FF00-B63F-84710C7967BB}"
           failureReason="TIME_TAKEN"
           statusCode="200"
           triggerStatusCode="0"
           timeTaken="1062"
           xmlns:freb="http://schemas.microsoft.com/win/2006/06/iis/freb"
           >

As far as I know, if you want to redirect all the request from admin.mysite.com to mysite.com/admin by using url rewrite. 据我所知,是否要使用url重写将所有请求从admin.mysite.com重定向到mysite.com/admin。

I suggest you could try below url rewrite rule: 我建议您可以尝试使用以下网址重写规则:

Notice: The match url part will not match the host url like admin.mysite.com . 注意:匹配网址部分将不匹配主机网址,例如admin.mysite.com It will just match the pattern part of the url like /admin/test . 它只会匹配url的模式部分,例如/admin/test

       <rule name="Rewrite sub-domain to dir">
           <match url=".*" />
           <conditions>
               <add input="{HTTP_HOST}" pattern="^admin\.mysite\.com$" />
           </conditions>
           <action type="Rewrite" url="http://example.com/admin/{R:0}" />
       </rule>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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